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
listlengths
1
5
how to override search_read() method in Odoo v.9?
38,651,051
<p><strong>Impacted versions: 9.0</strong></p> <p>I am try to restrict some products based on category. </p> <p>I have override <em>name_search()</em> method which work fine for <em>Many2one</em> field. But When I search product from search more option in <em>Many2one</em> field or search product from search menu in list view, it's show me that product. </p> <p>I have tried following code:</p> <pre><code>class ProductTemplate(models.Model): _inherit = "product.template" def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None): res = super(ProductTemplate, self).search_read(model, fields=fields, offset=offset, limit=limit, domain=domain, sort=sort) return res </code></pre> <p>But it's give me following trace-back.</p> <pre><code>2016-07-29 05:09:01,167 9750 ERROR enterprise openerp.http: Exception during JSON request handling. Traceback (most recent call last): File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 643, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 680, in dispatch result = self._call_function(**self.params) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 316, in _call_function return checked_call(self.db, *args, **kwargs) File "/home/odoo9/odoo-9.0e-20160127/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 309, in checked_call result = self.endpoint(*a, **kw) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 959, in __call__ return self.method(*args, **kw) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 509, in response_wrap response = f(*args, **kw) File "/home/odoo9/odoo-9.0e-20160127/openerp/addons/web/controllers/main.py", line 847, in search_read return self.do_search_read(model, fields, offset, limit, domain, sort) File "/home/odoo9/odoo-9.0e-20160127/openerp/addons/web/controllers/main.py", line 868, in do_search_read request.context) File "/home/odoo9/odoo-9.0e-20160127/openerp/http.py", line 1064, in proxy result = meth(cr, request.uid, *args, **kw) File "/home/odoo9/odoo-9.0e-20160127/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) TypeError: search_read() takes at most 7 arguments (9 given) </code></pre> <p><strong>Question</strong>:</p> <ol> <li><p>How to restrict User to by-pass selecting product from search menu ?</p></li> <li><p>How can I override <em>search_read()</em> method ?</p></li> </ol>
0
2016-07-29T05:24:49Z
38,655,553
<p>It should be something like this:</p> <pre class="lang-py prettyprint-override"><code>@api.model def search_read( self, domain=None, fields=None, offset=0, limit=None, order=None): res = super(Product, self).search_read( domain, fields, offset, limit, order) return res </code></pre>
1
2016-07-29T09:43:11Z
[ "python", "openerp", "odoo-8", "odoo-9" ]
How to remove arrow on tooltip from bokeh plot
38,651,060
<p>Is there a way to remove the little black pointer arrow that is on the tooltip (indicating the position of the mouse when the <code>point_policy='follow_mouse'</code>)? Any help appreciated</p> <p><a href="http://i.stack.imgur.com/6RJZu.png" rel="nofollow"><img src="http://i.stack.imgur.com/6RJZu.png" alt="enter image description here"></a></p>
1
2016-07-29T05:25:58Z
38,661,964
<p>The <em>answer</em> is that is is not currently any configuration option for this as of Bokeh <code>0.12.1</code>. </p> <hr> <p>Here is some additional information that may be useful, however. I'd encourage you to open an issue for discussion of this potential feature on the project issue tracker:</p> <p><a href="https://github.com/bokeh/bokeh/issues" rel="nofollow">https://github.com/bokeh/bokeh/issues</a></p> <p>It's possible that this could be accomplished with some CSS trick, but I don't know for certain. Alternatively, it is also now possible to extend Bokeh with your own custom extensions. You can find more information about writing custom extensions here:</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/extensions.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/extensions.html</a></p> <p>However, that would be at least a somewhat involved task, probably necessitating the kind of back-and for questions and help that StackOverflow is not well suited for. Please feel free to stop by the project <a href="https://groups.google.com/a/continuum.io/forum/?pli=1#!forum/bokeh" rel="nofollow">mailing list</a> or <a href="https://gitter.im/bokeh/bokeh" rel="nofollow">gitter chat channel</a> for that kind of assistance. </p>
1
2016-07-29T15:02:19Z
[ "python", "python-3.x", "bokeh" ]
How to remove arrow on tooltip from bokeh plot
38,651,060
<p>Is there a way to remove the little black pointer arrow that is on the tooltip (indicating the position of the mouse when the <code>point_policy='follow_mouse'</code>)? Any help appreciated</p> <p><a href="http://i.stack.imgur.com/6RJZu.png" rel="nofollow"><img src="http://i.stack.imgur.com/6RJZu.png" alt="enter image description here"></a></p>
1
2016-07-29T05:25:58Z
38,662,516
<p>As of Bokeh <strong>0.12.2</strong>, there is in option for that:</p> <pre><code>hover.show_arrow = False </code></pre> <p>This is a complete example, taken from the <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html#getting-started" rel="nofollow">official documentation</a>:</p> <pre><code>#!/usr/bin/env python # coding: utf-8 # from bokeh.plotting import figure, output_file, show from bokeh.models import HoverTool def main(): # prepare some data x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] # output to static HTML file output_file("lines.html") # create a new plot with a title and axis labels p = figure(title="simple line example", x_axis_label='x', y_axis_label='y', tools='hover') # add a line renderer with legend and line thickness p.line(x, y, legend="Temp.", line_width=2) # hover hover = p.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ ("Name", "@name"), ("Unemployment rate)", "@rate%"), ("(Long, Lat)", "($x, $y)"), ] # disable tooltip arrow hover.show_arrow = False # show the results show(p) return 0 if __name__ == '__main__': exit(main()) </code></pre> <hr> <p><em>(For history)</em></p> <p>As bigreddot said, I opened an <a href="https://github.com/bokeh/bokeh/issues/4906" rel="nofollow">issue</a> and I made a <a href="https://github.com/bokeh/bokeh/pull/4907" rel="nofollow">patch</a> to disable the arrow. If accepted, you will be able to disable the arrow with:</p> <pre><code>hover.show_arrow = False </code></pre>
1
2016-07-29T15:32:00Z
[ "python", "python-3.x", "bokeh" ]
How to generate a dict from string separated by semicolon?
38,651,123
<p>I am using Beautifulsoup to search for a specific number in HTML but got stuck here.</p> <pre><code>The raw data is: &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; </code></pre> <p>and I want to extract the "bookmarkable_id".</p> <pre><code>bsobj = BeautifulSoup(text,"html.parser") questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init'] </code></pre> <p>It returns to me a string with words separated by semicolons:</p> <pre><code>bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question' </code></pre> <p>But I don't know how I can extract from here. Please help!</p>
2
2016-07-29T05:31:16Z
38,651,207
<p>You can use re to search on questionID_line,</p> <pre><code>import re re.findall("bookmarkable_id='(.*?)'", questionID_line) </code></pre>
1
2016-07-29T05:38:47Z
[ "python", "beautifulsoup" ]
How to generate a dict from string separated by semicolon?
38,651,123
<p>I am using Beautifulsoup to search for a specific number in HTML but got stuck here.</p> <pre><code>The raw data is: &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; </code></pre> <p>and I want to extract the "bookmarkable_id".</p> <pre><code>bsobj = BeautifulSoup(text,"html.parser") questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init'] </code></pre> <p>It returns to me a string with words separated by semicolons:</p> <pre><code>bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question' </code></pre> <p>But I don't know how I can extract from here. Please help!</p>
2
2016-07-29T05:31:16Z
38,651,261
<p>Use <code>split()</code>:</p> <pre><code>data="bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question'" output = {i.split("=")[0].strip():i.split("=")[1].strip() for i in data.split(";")} </code></pre> <p>Output</p> <pre><code>{'bookmarks_path': "'/en-US/bookmarks'", 'bookmark_id': "''", 'bookmarked': 'false', 'bookmarkable_id': "'793447'", 'bookmarkable_type': "'Question'"} </code></pre> <p>Feel free to modify <code>strip()</code> according to your desired output.</p>
1
2016-07-29T05:42:48Z
[ "python", "beautifulsoup" ]
How to generate a dict from string separated by semicolon?
38,651,123
<p>I am using Beautifulsoup to search for a specific number in HTML but got stuck here.</p> <pre><code>The raw data is: &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; </code></pre> <p>and I want to extract the "bookmarkable_id".</p> <pre><code>bsobj = BeautifulSoup(text,"html.parser") questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init'] </code></pre> <p>It returns to me a string with words separated by semicolons:</p> <pre><code>bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question' </code></pre> <p>But I don't know how I can extract from here. Please help!</p>
2
2016-07-29T05:31:16Z
38,651,284
<p>Try this:</p> <pre><code>data = "bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question'" fields = {} for f in data.split('; '): k , v = f.split('=') fields[k] = v.strip("'") print(fields) </code></pre> <p>Gives:</p> <pre><code>{'bookmarked': 'false', 'bookmark_id': '', 'bookmarks_path': '/en-US/bookmarks', 'bookmarkable_type': 'Question', 'bookmarkable_id': '793447'} </code></pre>
4
2016-07-29T05:44:01Z
[ "python", "beautifulsoup" ]
How to generate a dict from string separated by semicolon?
38,651,123
<p>I am using Beautifulsoup to search for a specific number in HTML but got stuck here.</p> <pre><code>The raw data is: &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; </code></pre> <p>and I want to extract the "bookmarkable_id".</p> <pre><code>bsobj = BeautifulSoup(text,"html.parser") questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init'] </code></pre> <p>It returns to me a string with words separated by semicolons:</p> <pre><code>bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question' </code></pre> <p>But I don't know how I can extract from here. Please help!</p>
2
2016-07-29T05:31:16Z
38,651,409
<p>Try this</p> <pre><code>s = """ &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; """ import re data = re.findall("bookmark[^=]*='[^']*",s) dict1 = {} for j in (data): one,two = j.split("=") dict1[one] = two.strip("'") print dict1 </code></pre>
0
2016-07-29T05:53:13Z
[ "python", "beautifulsoup" ]
How to generate a dict from string separated by semicolon?
38,651,123
<p>I am using Beautifulsoup to search for a specific number in HTML but got stuck here.</p> <pre><code>The raw data is: &lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt; </code></pre> <p>and I want to extract the "bookmarkable_id".</p> <pre><code>bsobj = BeautifulSoup(text,"html.parser") questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init'] </code></pre> <p>It returns to me a string with words separated by semicolons:</p> <pre><code>bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question' </code></pre> <p>But I don't know how I can extract from here. Please help!</p>
2
2016-07-29T05:31:16Z
38,652,519
<p>If you don't remove the last <code>"; "</code> trying to unpack will cause an error as split will leave an odd empty string at the end:</p> <pre><code>from bs4 import BeautifulSoup html = """&lt;div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; "&gt;""" soup = BeautifulSoup(html) s = soup.select_one("div.box_content")['ng_init'] d = dict(sub.split("=", 1) for sub in s.strip("; ").split("; ")) </code></pre>
0
2016-07-29T07:06:03Z
[ "python", "beautifulsoup" ]
Why python doesn't have Garbage Collector thread?
38,651,571
<p>Java has daemon thread to monitor memory usage and do the gc task. From jstack I see</p> <pre><code>"main" #1 prio=5 os_prio=0 tid=0x00007f34b000e000 nid=0x808 waiting on condition [0x00007f34b6f02000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep(Native Method) .... "GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f34b0023000 nid=0x809 runnable "GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f34b0024800 nid=0x80a runnable "GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f34b0026800 nid=0x80b runnable </code></pre> <p>But speaking of python, I wrote a </p> <pre><code>#!/usr/bin/env python import gc import time gc.enable() while True: print "This prints once a minute." time.sleep(60) </code></pre> <p>I saw the the python process has only one thread,</p> <pre><code>$ cat /proc/1627/status Name: python ... Threads: 1 </code></pre> <p>The question is, why python doesn't have gc thread like Java? Then which thread does the gc task?</p>
0
2016-07-29T06:05:09Z
38,660,680
<p>If you start java with <code>-XX:+UseSerialGC</code> options you will not see any GC thread. For single threaded GC algorithm application thread can be used to do GC activities.</p> <p>Dedicated threads required for</p> <ul> <li>Parallel GC (you need more than single thread)</li> <li>Concurrent GC (GC activities running in parallel with application logic)</li> </ul>
1
2016-07-29T13:55:23Z
[ "python", "garbage-collection" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,651,757
<p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> (it does exactly what you want - groups consecutive elements) and count all groups which starts with <code>1</code>:</p> <pre><code>In [1]: from itertools import groupby In [2]: a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] In [3]: len([k for k, _ in groupby(a) if k == 1]) Out[3]: 5 </code></pre> <hr> <blockquote> <p>what if I wanted to add a condition that an event is given as long as there are is 2 or more '0's in between.</p> </blockquote> <p>This could be done using <code>groupby</code> and custom <code>key</code> function:</p> <pre><code>from itertools import groupby class GrouperFn: def __init__(self): self.prev = None def __call__(self, n): assert n is not None, 'n must not be None' if self.prev is None: self.prev = n return n if self.prev == 1: self.prev = n return 1 self.prev = n return n def count_events(events): return len([k for k, _ in groupby(events, GrouperFn()) if k == 1]) def run_tests(tests): for e, a in tests: c = count_events(e) assert c == a, 'failed for {}, expected {}, given {}'.format(e, a, c) print('All tests passed') def main(): run_tests([ ([0, 1, 1, 1, 0], 1), ([], 0), ([1], 1), ([0], 0), ([0, 0, 0], 0), ([1, 1, 0, 1, 1], 1), ([0, 1, 1, 0, 1, 1, 0], 1), ([1, 0, 1, 1, 0, 1, 1, 0, 0, 1], 2), ([1, 1, 0, 0, 1, 1], 2), ([0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0], 4) ]) if __name__ == "__main__": main() </code></pre> <p>The idea is pretty simple - when a <code>0</code> goes after a group of <code>1</code>'s, it could be a part of the group and therefore should be included in that group. The next event either continues the group (if the event is <code>1</code>) or splits it (if the event is <code>0</code>)</p> <p><em>Note, that presented approach will work only when you need to <strong>count</strong> a number of events, since it splits <code>[1, 1, 0, 0]</code> as <code>[[1, 1, 0], [0]]</code></em>.</p>
11
2016-07-29T06:17:48Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,651,947
<pre><code>def num_events(list): total = 0 in_event = 0 for current in list: if current and not in_event: total += 1 in_event = current return total </code></pre> <p>This function iterates over the list from the left side and every time it encounters a 1 immediately after a 0, it increments the counter. In other words, it adds 1 to the total count at the start of each event.</p>
1
2016-07-29T06:30:58Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,652,078
<p>Math way (be careful with an empty array):</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] events = (a[0] + a[-1] + sum(a[i] != a[i-1] for i in range(1, len(a)))) / 2 print events </code></pre> <p>I like to think this is efficient :)</p>
2
2016-07-29T06:40:08Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,652,189
<p>Try this</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] flag = 0 cnt = 0 for j in (a): if( j == 1): if(flag == 0): cnt += 1 flag = 1 elif (j == 0): flag = 0 print cnt </code></pre>
1
2016-07-29T06:46:12Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,652,540
<p>One more:</p> <pre><code>sum([(a[i] - a[i-1])&gt;0 for i in range(1, len(a))]) </code></pre>
1
2016-07-29T07:07:30Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,654,998
<p>Me being a simpleton ;-)</p> <pre><code>def get_number_of_events(event_list): num_of_events = 0 for index, value in enumerate(event_list): if 0 in (value, index): continue elif event_list[index-1] == 0: num_of_events += 1 return num_of_events </code></pre>
0
2016-07-29T09:16:20Z
[ "python", "arrays", "time-series" ]
count number of events in an array python
38,651,692
<p>I have the following array:</p> <pre><code>a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] </code></pre> <p>Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:</p> <pre><code>b = [5] </code></pre> <p>Thanks</p>
4
2016-07-29T06:13:46Z
38,656,060
<p>To replace multiple occurrence with single occurrence, append each item in a list if only the last appended item is not equal to the current one, and do the count.</p> <pre><code>def count_series(seq): seq = iter(seq) result = [next(seq, None)] for item in seq: if result[-1] != item: result.append(item) return result a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] count_series(a).count(1) 5 </code></pre>
0
2016-07-29T10:06:12Z
[ "python", "arrays", "time-series" ]
Defining function using if-statement
38,651,714
<pre><code>def roots4(a,b,c,d): d = b * b - 4 * a * c if a != 0 and d == 0: roots4(a,b,c,d) x = -b/ (2*a) if a != 0 and d &gt; 0: roots4(a,b,c,d) x1 = (-b + math.sqrt(d)) / 2.0 / a x2 = (-b - math.sqrt(d)) / 2.0 / a if a != 0 and d &lt; 0: roots4(a,b,c,d) xre = (-b) / (2*a) xim = (math.sqrt(d))/ (2*a) print x1 = xre + ixim strx1 = "x2 = %6.2f + i %6.2f" %(xre, xim) print strx1 </code></pre> <p>This is part of my code for a project. What I'm trying to do is define <code>roots4(a,b,c,d)</code>. For example, in the case that <code>a != 0 and d == 0</code> then <code>roots4(a,b,c,d)</code> shall then go to to finding <code>x</code> by solving equation <code>x = -b/ (2*a)</code>. And so on... I don't know what I'm doing wrong. Any tips?</p>
0
2016-07-29T06:14:57Z
38,652,998
<p>Well, it looks like you have made an infinite loop with your recursive functions. As it looks now you will never do any calculations apart from </p> <pre><code>d = b * b - 4 * a * c </code></pre> <p>over and over again.</p> <p>Consider the program flow. Each time you reach </p> <pre><code>roots4(a,b,c,d) </code></pre> <p>you will end up in the top again.</p>
0
2016-07-29T07:31:17Z
[ "python", "python-2.7", "function", "if-statement", "printing" ]
Defining function using if-statement
38,651,714
<pre><code>def roots4(a,b,c,d): d = b * b - 4 * a * c if a != 0 and d == 0: roots4(a,b,c,d) x = -b/ (2*a) if a != 0 and d &gt; 0: roots4(a,b,c,d) x1 = (-b + math.sqrt(d)) / 2.0 / a x2 = (-b - math.sqrt(d)) / 2.0 / a if a != 0 and d &lt; 0: roots4(a,b,c,d) xre = (-b) / (2*a) xim = (math.sqrt(d))/ (2*a) print x1 = xre + ixim strx1 = "x2 = %6.2f + i %6.2f" %(xre, xim) print strx1 </code></pre> <p>This is part of my code for a project. What I'm trying to do is define <code>roots4(a,b,c,d)</code>. For example, in the case that <code>a != 0 and d == 0</code> then <code>roots4(a,b,c,d)</code> shall then go to to finding <code>x</code> by solving equation <code>x = -b/ (2*a)</code>. And so on... I don't know what I'm doing wrong. Any tips?</p>
0
2016-07-29T06:14:57Z
38,653,309
<p>As pointed out in comments and jimmy's answer, there's no need for recursive calls.</p> <p>Here's an example of how you could correct it (adapt it the way you like):</p> <pre><code>#!/usr/bin/env python2 # -*- coding: utf-8 -*- import math def roots4(a, b, c): """Prints the solutions of ax² + bx + c = 0, if a != 0""" if a == 0: print 'This function is meant to solve a 2d degree equation, '\ 'not a 1st degree one.' else: d = b * b - 4 * a * c solutions = [] if d == 0: solutions = [str(-b / (2 * a))] elif d &gt; 0: solutions = [str((-b + math.sqrt(d)) / 2.0 / a), str((-b - math.sqrt(d)) / 2.0 / a)] elif d &lt; 0: xre = str((-b) / (2 * a)) xim = str((math.sqrt(-d)) / (2 * a)) solutions = [xre + " + i" + xim, xre + " - i" + xim] print "\nEquation is: {}x² + {}x + {} = 0".format(a, b, c) if len(solutions) == 1: print "There's only one solution: " + solutions[0] else: print "Solutions are: " + " and ".join(solutions) roots = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 2.0, 4.0), (1.0, 2.0, 1.0), (1.0, -5.0, 6.0), (1.0, 2.0, 3.0)] for r in roots: roots4(*r) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>$ ./test_script2.py This function is meant to solve a 2d degree equation, not a 1st degree one. This function is meant to solve a 2d degree equation, not a 1st degree one. This function is meant to solve a 2d degree equation, not a 1st degree one. Equation is: 1.0x² + 2.0x + 1.0 = 0 There's only one solution: -1.0 Equation is: 1.0x² + -5.0x + 6.0 = 0 Solutions are: 3.0 and 2.0 Equation is: 1.0x² + 2.0x + 3.0 = 0 Solutions are: -1.0 + i1.41421356237 and -1.0 - i1.41421356237 </code></pre>
0
2016-07-29T07:49:48Z
[ "python", "python-2.7", "function", "if-statement", "printing" ]
Defining function using if-statement
38,651,714
<pre><code>def roots4(a,b,c,d): d = b * b - 4 * a * c if a != 0 and d == 0: roots4(a,b,c,d) x = -b/ (2*a) if a != 0 and d &gt; 0: roots4(a,b,c,d) x1 = (-b + math.sqrt(d)) / 2.0 / a x2 = (-b - math.sqrt(d)) / 2.0 / a if a != 0 and d &lt; 0: roots4(a,b,c,d) xre = (-b) / (2*a) xim = (math.sqrt(d))/ (2*a) print x1 = xre + ixim strx1 = "x2 = %6.2f + i %6.2f" %(xre, xim) print strx1 </code></pre> <p>This is part of my code for a project. What I'm trying to do is define <code>roots4(a,b,c,d)</code>. For example, in the case that <code>a != 0 and d == 0</code> then <code>roots4(a,b,c,d)</code> shall then go to to finding <code>x</code> by solving equation <code>x = -b/ (2*a)</code>. And so on... I don't know what I'm doing wrong. Any tips?</p>
0
2016-07-29T06:14:57Z
38,653,633
<p>you probably stacked with</p> <pre><code> ... roots4(a,b,c,d) ... </code></pre> <p>this causes an infinite loop</p> <p>firstly, why do you need a recursion call? what's <code>d</code> parameter for?</p> <p>secondly, what is <code>ixim</code>? should it be something like <code>xim * 1j</code>? what do you expect from <code>print x1 = xre + ixim</code>?</p> <p>if you want print only in case when <code>d &lt; 0</code> this will be fine</p> <pre><code> from math import sqrt def roots4(a,b,c): if a != 0.: x_left = -b/(2*a) d = b * b - 4 * a * c if d == 0.: x_right = 0. elif d &gt; 0.: x_right = sqrt(d) / (2 * a) else: xim = sqrt(-d) / (2 * a) strx1 = "x1 = %6.2f + i %6.2f" %(x_left, xim) print strx1 strx2 = "x2 = %6.2f - i %6.2f" %(x_left, xim) print strx2 x_right = xim * 1j x1 = x_left + x_right x2 = x_left - x_right else: raise ValueError("incorrect leading coefficient in given square equation") </code></pre>
0
2016-07-29T08:05:47Z
[ "python", "python-2.7", "function", "if-statement", "printing" ]
print UTF-8 character in Python 2.7
38,651,993
<p>Here is how I open, read and output. The file is an UTF-8 encoded file for unicode characters. I want to print the first 10 UTF-8 characters, but the output from below code snippet print 10 weird unrecognized characters. Wondering if anyone have any ideas how to print correctly? Thanks.</p> <pre><code> with open(name, 'r') as content_file: content = content_file.read() for i in range(10): print content[i] </code></pre> <p>Each of the 10 weird character looks like this,</p> <pre><code>� </code></pre> <p>regards, Lin</p>
2
2016-07-29T06:33:57Z
38,652,100
<p>To output a Unicode string to a file or to the console you need to choose a text encoding. In Python the default text encoding is ASCII, but to support other characters you need to use a different encoding, such as UTF-8:</p> <pre><code>s = unicode(your_object).encode('utf8') print s </code></pre>
2
2016-07-29T06:41:19Z
[ "python", "python-2.7", "unicode", "utf-8" ]
print UTF-8 character in Python 2.7
38,651,993
<p>Here is how I open, read and output. The file is an UTF-8 encoded file for unicode characters. I want to print the first 10 UTF-8 characters, but the output from below code snippet print 10 weird unrecognized characters. Wondering if anyone have any ideas how to print correctly? Thanks.</p> <pre><code> with open(name, 'r') as content_file: content = content_file.read() for i in range(10): print content[i] </code></pre> <p>Each of the 10 weird character looks like this,</p> <pre><code>� </code></pre> <p>regards, Lin</p>
2
2016-07-29T06:33:57Z
38,653,062
<p>When Unicode codepoints (characters) are encoded as UTF-8 some codepoints are converted to a single byte, but many codepoints become more than one byte. Characters in the standard 7 bit ASCII range will be encoded as single bytes, but more exotic characters will generally require more bytes to encode. </p> <p>So you are getting those weird characters because you are breaking up those multi-byte UTF-8 sequences into single bytes. Sometime those bytes will correspond to normal printable characters, but often they won't so you get � printed instead.</p> <p>Here's a short demo using the ©, ®, and ™ characters, which are encoded as 2, 2, and 3 bytes respectively in UTF-8. My terminal is set to use UTF-8.</p> <pre><code>utfbytes = "\xc2\xa9 \xc2\xae \xe2\x84\xa2" print utfbytes, len(utfbytes) for b in utfbytes: print b, repr(b) uni = utfbytes.decode('utf-8') print uni, len(uni) </code></pre> <p><strong>output</strong></p> <pre><code>© ® ™ 9 � '\xc2' � '\xa9' ' ' � '\xc2' � '\xae' ' ' � '\xe2' � '\x84' � '\xa2' © ® ™ 5 </code></pre> <p>Stack Overflow co-founder, Joel Spolsky, has written a good article on Unicode: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></p> <p>You should also take a look at the <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Unicode HOWTO</a> article in the Python docs, and Ned Batchelder's <a href="http://nedbatchelder.com/text/unipain.html" rel="nofollow">Pragmatic Unicode</a> article, aka "Unipain".</p> <hr> <p>Here's a short example of extracting individual characters from a UTF-8 encoded byte string. As I mention in the comments, to do this correctly you need to know how many bytes each of the characters is encoded as.</p> <pre><code>utfbytes = "\xc2\xa9 \xc2\xae \xe2\x84\xa2" widths = (2, 1, 2, 1, 3) start = 0 for w in widths: print "%d %d [%s]" % (start, w, utfbytes[start:start+w]) start += w </code></pre> <p><strong>output</strong></p> <pre><code>0 2 [©] 2 1 [ ] 3 2 [®] 5 1 [ ] 6 3 [™] </code></pre> <p>FWIW, here's a Python 3 version of that code:</p> <pre><code>utfbytes = b"\xc2\xa9 \xc2\xae \xe2\x84\xa2" widths = (2, 1, 2, 1, 3) start = 0 for w in widths: s = utfbytes[start:start+w] print("%d %d [%s]" % (start, w, s.decode())) start += w </code></pre> <p>If we don't know the byte widths of the characters in our UTF-8 string then we need to do a little more work. Each UTF-8 sequence encodes the width of the sequence in the first byte, as described in <a href="https://en.wikipedia.org/wiki/UTF-8#Description" rel="nofollow">the Wikipedia article on UTF-8</a>.</p> <p>The following Python 2 demo shows how you can extract that width information; it produces the same output as the two previous snippets.</p> <pre><code># UTF-8 code widths #width starting byte #1 0xxxxxxx #2 110xxxxx #3 1110xxxx #4 11110xxx #C 10xxxxxx def get_width(b): if b &lt;= '\x7f': return 1 elif '\x80' &lt;= b &lt;= '\xbf': #Continuation byte raise ValueError('Bad alignment: %r is a continuation byte' % b) elif '\xc0' &lt;= b &lt;= '\xdf': return 2 elif '\xe0' &lt;= b &lt;= '\xef': return 3 elif '\xf0' &lt;= b &lt;= '\xf7': return 4 else: raise ValueError('%r is not a single byte' % b) utfbytes = b"\xc2\xa9 \xc2\xae \xe2\x84\xa2" start = 0 while start &lt; len(utfbytes): b = utfbytes[start] w = get_width(b) s = utfbytes[start:start+w] print "%d %d [%s]" % (start, w, s) start += w </code></pre> <p>Generally, it should <em>not</em> be necessary to do this sort of thing: just use the provided decoding methods.</p> <hr> <p>For the curious, here's a Python 3 version of <code>get_width</code>, and a function that decodes a UTF-8 bytestring manually.</p> <pre><code>def get_width(b): if b &lt;= 0x7f: return 1 elif 0x80 &lt;= b &lt;= 0xbf: #Continuation byte raise ValueError('Bad alignment: %r is a continuation byte' % b) elif 0xc0 &lt;= b &lt;= 0xdf: return 2 elif 0xe0 &lt;= b &lt;= 0xef: return 3 elif 0xf0 &lt;= b &lt;= 0xf7: return 4 else: raise ValueError('%r is not a single byte' % b) def decode_utf8(utfbytes): start = 0 uni = [] while start &lt; len(utfbytes): b = utfbytes[start] w = get_width(b) if w == 1: n = b else: n = b &amp; (0x7f &gt;&gt; w) for b in utfbytes[start+1:start+w]: if not 0x80 &lt;= b &lt;= 0xbf: raise ValueError('Not a continuation byte: %r' % b) n &lt;&lt;= 6 n |= b &amp; 0x3f uni.append(chr(n)) start += w return ''.join(uni) utfbytes = b'\xc2\xa9 \xc2\xae \xe2\x84\xa2' print(utfbytes.decode('utf8')) print(decode_utf8(utfbytes)) </code></pre> <p><strong>output</strong></p> <p>© ® ™<br> © ® ™</p>
4
2016-07-29T07:34:57Z
[ "python", "python-2.7", "unicode", "utf-8" ]
Traceback (most recent call last): File "<pyshell#439>", line 3, in <module> print(l.text) AttributeError: 'list' object has no attribute 'text'
38,652,058
<p>I am currently scraping Linkedin Job directory using selenium in python shell</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&amp;f_TP=1%2C2&amp;orig=FCTD&amp;trk=jobs_jserp_posted_one_week') a = driver.find_elements_by_class_name('job-title-text') b = driver.find_elements_by_class_name('company-name-text') c = driver.find_elements_by_class_name('job-location') d = driver.find_elements_by_class_name('job-description') #There are 50 pages of jobs therefore I specified a range of 55 for e in range(55): for g in a: print(g.text) for h in b: print(h.text) for i in c: print(i.text) for j in d: print(j.text) k = driver.find_element_by_class_name('next-btn') k.click() Job = [] Job.append(a) Job.append(b) Job.append(c) Job.append(d) for e in range(55): for l in Job: print(l.text) k = driver.find_element_by_class_name('next-btn') k.click() </code></pre> <p>This code is not working and I have been struggling and tried various methods of solving this issue. It will be great if I can get the correct solution. </p>
1
2016-07-29T06:38:59Z
38,652,517
<p>Thats because you will get multidemensional array in <code>Job</code>. Try to replace </p> <pre><code> Job.append(a) Job.append(b) Job.append(c) Job.append(d) </code></pre> <p>with </p> <pre><code>Job += a Job += b Job += c Job += d </code></pre>
0
2016-07-29T07:05:57Z
[ "python", "selenium" ]
Traceback (most recent call last): File "<pyshell#439>", line 3, in <module> print(l.text) AttributeError: 'list' object has no attribute 'text'
38,652,058
<p>I am currently scraping Linkedin Job directory using selenium in python shell</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&amp;f_TP=1%2C2&amp;orig=FCTD&amp;trk=jobs_jserp_posted_one_week') a = driver.find_elements_by_class_name('job-title-text') b = driver.find_elements_by_class_name('company-name-text') c = driver.find_elements_by_class_name('job-location') d = driver.find_elements_by_class_name('job-description') #There are 50 pages of jobs therefore I specified a range of 55 for e in range(55): for g in a: print(g.text) for h in b: print(h.text) for i in c: print(i.text) for j in d: print(j.text) k = driver.find_element_by_class_name('next-btn') k.click() Job = [] Job.append(a) Job.append(b) Job.append(c) Job.append(d) for e in range(55): for l in Job: print(l.text) k = driver.find_element_by_class_name('next-btn') k.click() </code></pre> <p>This code is not working and I have been struggling and tried various methods of solving this issue. It will be great if I can get the correct solution. </p>
1
2016-07-29T06:38:59Z
38,652,842
<p>I think that's because variable "a" is a list. You can debug to see what's in Job list. I think the Job list like this Job=[[a], [b], [c], [d]] in your code.</p>
0
2016-07-29T07:23:44Z
[ "python", "selenium" ]
Issues using slots and signals when connecting two windows in Qt using PyQt
38,652,324
<p>I am having trouble passing a line of text from one LineEdit in a window to a lineEdit in another window by clicking a button. I have read multiple examples but I can't seem to get the signal to display on the second window. This is a very paired down version of the app I'm creating. I hope y'all can see something I can't. The second window will open when the button in the first window is clicked, but nothing happens.</p> <p>Thanks</p> <pre><code>import sys from PyQt4 import QtGui, QtCore class Window1(QtGui.QMainWindow): textSaved = QtCore.pyqtSignal(str) def __init__(self): super(Window1,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Signal Emitter") self.home() def home(self): self.__line=QtGui.QLineEdit("howdy", self) self.__line.move(120,100) btn=QtGui.QPushButton("Send Signal", self) btn.clicked.connect(self.send_signal) btn.move(0,100) self.show() def send_signal(self): signal=self.__line.displayText() self.textSaved.emit(signal) self.Window2=Window2() self.Window2.show() class Window2(QtGui.QMainWindow): def __init__(self): super(Window2,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Slot Receiver") self.home() def home(self): self.line_response=QtGui.QLineEdit(None, self) self.line_response.move(120,100) self.__main=Window1() self.__main.textSaved.connect(self.showMessage) @QtCore.pyqtSlot() def showMessage(self, message): self.bigbox(self, "The message is:"+ message) self.show() def run(): app=QtGui.QApplication(sys.argv) GUI=Window1() sys.exit(app.exec_()) run() </code></pre>
0
2016-07-29T06:54:16Z
38,664,888
<p>Alright so there are a few ways you can do this. You're on the right track for the signal slot thing. However, since you have multiple calls in each class to the other class, things get a little messed up.</p> <p>One way to solve your problem is to simply change the <code>__init__</code> function for your <code>Window2</code> class so that it accepts text, and sets the <code>QLineEdit</code> text to the inputted text. This will work once. When you click the button, the second window will show, and subsequent clicks won't change the text. Look below if you want the button to always update the text in the other window.</p> <p><strong>One time click</strong></p> <pre><code>import sys from PyQt4 import QtGui, QtCore class Window1(QtGui.QMainWindow): textSaved = QtCore.pyqtSignal(str) def __init__(self): super(Window1,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Signal Emitter") self.home() def home(self): self.__line=QtGui.QLineEdit("howdy", self) self.__line.move(120,100) btn=QtGui.QPushButton("Send Signal", self) btn.clicked.connect(self.send_signal) btn.move(0,100) self.show() def send_signal(self): signal=self.__line.displayText() self.textSaved.emit(signal) self.Window2=Window2(signal) # instantiate Window2 with the text self.Window2.show() class Window2(QtGui.QMainWindow): def __init__(self, txt): self.text = txt super(Window2,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Slot Receiver") self.home() def home(self): self.line_response=QtGui.QLineEdit(self.text, self) self.line_response.move(120,100) @QtCore.pyqtSlot() def showMessage(self, message): self.bigbox(self, "The message is:"+ message) self.show() def run(): app=QtGui.QApplication(sys.argv) GUI=Window1() sys.exit(app.exec_()) run() </code></pre> <p>I also don't know what <code>self.bigbox</code> is, do you want that to update? When I tried running it, I changed it to <code>self.line_response</code> because that's what I thought you meant. </p> <p>This solution will work in the sense that when you click the Send Signal button on <code>Window1</code>, you will get <code>Window2</code> with the contents of the <code>QLineEdit</code> of the first window in the corresponding one in the second window. </p> <p>If you want these two windows to be linked so that whenever you press that button, the second window's <code>QLineEdit</code> will change again to the current text in <code>Window1</code>, you can add a simple if else statement in your <code>send_signal</code> method inside your first class. You will also need to pass the actual <code>Window1</code> class into <code>Window2</code></p> <p>If it's the first time pressing the button, instantiate the <code>Window2</code> class with the current text. If it's the second + time pressing the button, you can emit a signal from class one and change the text in the second class. Here's some code that works this way:</p> <p><strong>Linked windows</strong></p> <pre><code>import sys from PyQt4 import QtGui, QtCore class Window1(QtGui.QMainWindow): textSaved = QtCore.pyqtSignal(str) def __init__(self): super(Window1,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Signal Emitter") self.home() self.counter = 0 def home(self): self.__line=QtGui.QLineEdit("howdy", self) self.__line.move(120,100) btn=QtGui.QPushButton("Send Signal", self) btn.clicked.connect(self.send_signal) btn.move(0,100) self.show() def send_signal(self): if self.counter == 0: signal=self.__line.displayText() self.Window2=Window2(signal, self) self.Window2.show() self.textSaved.connect(self.Window2.showMessage) self.counter = 1 else: signal = self.__line.displayText() self.textSaved.emit(signal) class Window2(QtGui.QDialog): def __init__(self, txt, window1): self.text = txt self.signal1 = window1.textSaved super(Window2,self).__init__() self.setGeometry(50,50,500,300) self.setWindowTitle("PyQt Signal Slot Receiver") self.home() self.signal1.connect(self.showMessage) def home(self): self.line_response=QtGui.QLineEdit(self.text, self) self.line_response.move(120,100) def showMessage(self, message): self.line_response.setText(message) def run(): app=QtGui.QApplication(sys.argv) GUI=Window1() sys.exit(app.exec_()) run() </code></pre> <p>If you have any questions, please comment! I wrote this kinda quickly; I will edit with more explanations when I have more time!</p>
0
2016-07-29T17:59:08Z
[ "python", "qt", "pyqt", "signals", "slots" ]
How do I work on multiple appengine projects with python?
38,652,358
<p>I need to export my blobstore from one appengine project and upload it to another project. How can I switch between projects programmatically with python?</p>
0
2016-07-29T06:57:12Z
38,657,617
<p>If by "python" you mean a python GAE app's code itself - AFAIK you can't switch apps - each such code runs only inside the app specified in the <code>.yaml</code> file.</p> <p>You could teach the exporting app project to serve the blob and for the actual transfer you could either:</p> <ul> <li>have the receving app directly pulling the blobs from the exporting app</li> <li>have an external (python) script pull blobs from the exporting apps and uploading them to the importing app.</li> </ul> <p>Either way you'd need to write some code to actually perform the transfer.</p> <p>So instead of doing that, I'd rather write and execute a one-time conversion script to move the data from blobstore (presently shown in the <a href="https://cloud.google.com/appengine/docs/python/" rel="nofollow">GAE python docs</a> under <code>Storing Data</code> > <strong><code>Superseded Storage Solutions</code></strong> section on the left-side menubar) to the Datastore or GCS, both of which have better backup/restore options, including across apps :) GCS can probably be even used to share the same data across apps. And you can still serve the GCS data using the blobstore API, see <a href="http://stackoverflow.com/questions/37225000/uploading-files-directly-to-google-cloud-storage-for-gae-app/37227087#37227087">Uploading files directly to Google Cloud Storage for GAE app</a></p> <p>If you mean some external python app code - AFAIK the blobstore doesn't offer generic access directly to an external application (I <em>might</em> be wrong, tho). So an external app would need to go through the regular upload/download handlers of the 2 apps. So in this case switching between projects really means switching between the 2 apps' upload/download URLs.</p> <p>Even for this scenario it might be worthy to migrate to GCS, which does offer direct access, see <a href="https://cloud.google.com/storage/docs/collaboration" rel="nofollow">Sharing and Collaboration</a></p>
0
2016-07-29T11:24:11Z
[ "python", "google-app-engine", "blobstore" ]
Cython callback segfaults using python-c-api calls
38,652,486
<p>Working on a control of an eGige camera, having a C library, I've started a <a href="http://cython.org/" rel="nofollow">cython</a> code <a href="https://github.com/srgblnch/python-pylon" rel="nofollow">project</a> with the idea to have the best things of each language.</p> <p>The library provides a way to listen a heartbeat from the camera to know if it has been disconnected. The callback with in a C++ class I've already did, but from this C++ class, call a python method of a class is falling into a <em>Segmentation fault</em> in all the ways I've tried.</p> <p>I've encapsulated it in a specific C++ class:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Python.h&gt; /* (...) */ PyCallback::PyCallback(PyObject* self, const char* methodName) { Py_XINCREF(self); _self = self; _method = PyObject_GetAttrString(self, methodName); } PyCallback::~PyCallback() { Py_XDECREF(_self); } void PyCallback::execute() { try { PyObject *args = PyTuple_Pack(1,_self); PyObject_CallFunctionObjArgs(_method, args); }catch(...){ _error("Exception calling python"); } } </code></pre> <p>From a cython object the code is:</p> <pre class="lang-py prettyprint-override"><code>cdef class Camera(...): # (...) cdef registerRemovalCallback(self): cdef: PyCallback* obj obj = new PyCallback(&lt;PyObject*&gt; self, &lt;char*&gt; "cameraRemovalCallback") cdef cameraRemovalCallback(self): self._isPresent = False </code></pre> <p>The lowest part of the backtrace it's just when try to prepare the arguments.</p> <pre><code>#0 0x00007ffff7b24592 in PyErr_Restore () from /usr/lib64/libpython2.6.so.1.0 #1 0x00007ffff7b23fef in PyErr_SetString () from /usr/lib64/libpython2.6.so.1.0 #2 0x00007ffff7b314dd in ?? () from /usr/lib64/libpython2.6.so.1.0 #3 0x00007ffff7b313ca in ?? () from /usr/lib64/libpython2.6.so.1.0 #4 0x00007ffff7b316c1 in ?? () from /usr/lib64/libpython2.6.so.1.0 #5 0x00007ffff7b31d2f in ?? () from /usr/lib64/libpython2.6.so.1.0 #6 0x00007ffff7b31e9c in Py_BuildValue () from /usr/lib64/libpython2.6.so.1.0 #7 0x00007ffff637cbf8 in PyCallback::execute (this=0x16212a0) at pylon/PyCallback.cpp:53 #8 0x00007ffff6376248 in CppCamera::removalCallback (this=0x161fb30, pDevice=&lt;value optimized out&gt;) at pylon/Camera.cpp:387 </code></pre> <p>I've tried to make the arguments using _Py_BuildValue("(self)", <em>self);</em> but then I've got a <em>segfault</em> there.</p> <p>I've tried also with <em>PyObject_CallFunctionObjArgs</em> with <em>NULL</em> in the arguments field, thinking that perhaps the pointer to "<em>self</em>" is already embedded as the method point to an specific address with in this object. But them I've got the <em>segfault</em> there.</p> <p>Do anyone see my mistake? Something there that shall be made in a different way? I hope this is a misunderstanding from my side about who to do that.</p> <p><strong>Update</strong> @ <em>2016/08/01</em>:</p> <p>Following comments indications, two modifications are made in the code:</p> <p>First of all the pointer storage to the <em>PyCallback</em> has been stored as a member of the <em>Camera</em> cython class:</p> <pre class="lang-py prettyprint-override"><code>cdef class Camera(...): cdef: #(...) PyCallback* _cbObj # (...) cdef registerRemovalCallback(self): self._cbObj = new PyCallback(&lt;PyObject*&gt; self, &lt;char*&gt; "cameraRemovalCallback") cdef cameraRemovalCallback(self): self._isPresent = False </code></pre> <p>Even this is a fundamental source of <em>segfaults</em> it looks it wasn't involved in the current one.</p> <p>Then PyCallback::execute() in the c++, I've made some changes. After reading about the <em>GIL</em> (Global Interpreter Lock) and add some calls for it, I've added a check that may guide to the solution:</p> <pre class="lang-cpp prettyprint-override"><code>PyCallback::PyCallback(PyObject* self, const char* methodName) { Py_Initialize(); Py_XINCREF(self); _self = self; _method = PyObject_GetAttrString(self, methodName); } PyCallback::~PyCallback() { Py_XDECREF(_self); Py_Finalize(); } void PyCallback::execute() { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); try { if ( PyCallable_Check(_method) ) { _info("Build arguments and call method"); PyObject *args = Py_BuildValue("(O)", _self); PyObject *kwargs = Py_BuildValue("{}", "", NULL); PyObject_Call(_method, args, kwargs); } else { _warning("The given method is not callable!"); } } catch(...) { // TODO: collect and show more information about the exception _error("Exception calling python"); } PyGILState_Release(gstate); } </code></pre> <p>Even I'm not sure how to do the call, the main point is that the _PyCallable_Check_ returns false.</p> <p>I've also tested to use the <em>typedef</em> option and <em>C</em> pointer to function to call it with the same <em>segfault</em> result.</p> <p><strong>Update</strong> @ <em>2016/08/03</em>:</p> <p>I've proceed with the suggested modifications. <code>cameraRemovalCallback</code> is now changed from <code>cdef</code> to <code>def</code> and some <code>if</code>s in the <code>PyCallback</code> reports that the method now is found. Also has been added to <code>~PyCallback()</code> a call to <code>Py_XDECREF(_method)</code> in case it was found in the constructor. The useless <code>try-catch</code> has been also removed.</p> <p>From the reference to the <a href="https://docs.python.org/2/c-api/object.html" rel="nofollow">Python's Object protocol</a>, that <a href="http://stackoverflow.com/users/4657412/davidw">DavidW</a> mention, I've check many of the <code>*Call*</code>combinations: falling to the segfault.</p> <p>I think this question is becoming <em>dirty</em> and is getting the appearance of a <em>forum</em> (question->answer->replay->...). I'm sorry about that, and I'll try to, next time I'll write, tell the segfault was solve and just what was.</p>
0
2016-07-29T07:04:10Z
38,729,464
<p>I'm not promising this is the only issue, but this is certainly <em>an</em> issue:</p> <p><code>cameraRemovalCallback</code> is a <code>cdef</code> function. This means that the function is purely accessible from C/Cython, but not accessible from Python. This means that <code>PyObject_GetAttrString</code> fails (since <code>cameraRemovalCallback</code> is not a Python attribute).</p> <p>You should define <code>cameraRemovalCallback</code> with <code>def</code> instead of <code>cdef</code> and that was it will be accessible through normal Python mechanisms. You should also check the result of <code>PyObject_GetAttrString</code> - if it returns <code>NULL</code> then it has failed to find the attribute.</p> <p>Therefore you end up trying to call <code>NULL</code> as a Python function.</p> <hr> <p>Other smaller issues:</p> <p>You should decref <code>_method</code> in <code>~PyCallback</code>.</p> <p>You should <em>not</em> call <code>Py_Initialize</code> and <code>Py_Finalize</code>. You seem to be creating the class from within Python anyway so it doesn't need initializing or finalizing. Finalizing will definitely cause you problems.</p> <p>I don't think you need to pass <code>self</code> as an argument to <code>PyObject_Call</code>. (I could be wrong though)</p> <p>The Python C api won't raise C++ exceptions, so your <code>try{} catch(...)</code> is never going to catch anything. Instead check the return values.</p> <p>You need to decref the results of both calls of <code>Py_BuildValue</code> (when you're done with them) also the result of <code>PyObject_Call</code>. If you don't do this you're leaking memory.</p> <hr> <p>The following complete example works for me (with Python 3.5 - I can't easily test it with earlier versions). If it works for you then you probably need to identify what's different in your case? If it doesn't work for you then it's more mysterious.</p> <p>pycallback.hpp:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdexcept&gt; inline PyObject* getCallable(PyObject* o, const char* methodName) { // assume o is not null PyObject* callable = PyObject_GetAttrString(o,methodName); if (callable == nullptr) { throw std::runtime_error("Attribute does not exist"); } return callable; } class PyCallback { private: PyObject* _callable; public: PyCallback(PyObject* callable) { // assume callable isn't null if (!PyCallable_Check(callable)) { throw std::runtime_error("object passed to PyCallback is not callable"); } _callable = callable; Py_XINCREF(_callable); } PyCallback(PyObject* o, const char* methodName) : PyCallback(getCallable(o,methodName)) { // needs C++11 to compile } // don't define copy operators PyCallback(const PyCallback&amp;) = delete; PyCallback&amp; operator=(const PyCallback&amp;) = delete; ~PyCallback() { Py_XDECREF(_callable); } void execute() { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); PyObject* result = PyObject_CallFunctionObjArgs(_callable,nullptr); Py_XDECREF(result); // allowed to be null PyGILState_Release(gstate); } }; </code></pre> <p>camera.pyx</p> <pre><code>cdef extern from "pycallback.hpp": cdef cppclass PyCallback: PyCallback(object) except + PyCallback(object, const char*) except + void execute() cdef class Camera: cdef PyCallback* o cdef public ispresent def __init__(self): self.o = NULL self.ispresent = True def registerRemovalCallback(self): self.o = new PyCallback(self,'cameraRemovalCallback') #self.o = new PyCallback(self.cameraRemovalCallback) def cameraRemovalCallback(self): self.ispresent = False def triggerCallback(self): if self.o != NULL: self.o.execute() </code></pre> <p>setup.py</p> <pre><code>from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( ext_modules = [ Extension('camera',sources=["camera.pyx"], language="c++", extra_compile_args=['-std=c++11'])], cmdclass={'build_ext': build_ext}) </code></pre> <p>test.py</p> <pre><code>import camera c = camera.Camera() print(c.ispresent) c.triggerCallback() print(c.ispresent) c.registerRemovalCallback() print(c.ispresent) c.triggerCallback() print(c.ispresent) </code></pre> <p>Note - there is a minor problem with this. <code>Camera</code> and the callback it holds form a reference loop so they never get freed. This causes a small memory leak, but it won't cause a segmentation fault.</p>
1
2016-08-02T20:02:09Z
[ "python", "c++", "cython", "python-c-api" ]
Pandas - different aggregations for a field
38,652,621
<p>I have a transaction table with these columns: customer_id, transaction_id, month</p> <p>I would like to write a query which will be equivalent to the following in SQL:</p> <pre><code>SELECT min(month) as first_month, max(month) as last_month FROM transactions GROUP BY customer_id </code></pre> <p>in pandas, it seems I can only aggregate every column once, e.g the following query will return only one month column: </p> <pre><code>transactions.groupby('customer_id').aggregate({ 'Month' : 'min', 'Month' : 'max'}) </code></pre> <p>Any ideas how can I achieve this?</p>
0
2016-07-29T07:12:05Z
38,652,664
<p>You can use:</p> <pre><code>transactions.groupby('customer_id').aggregate({ 'Month' : ['min', 'max']}) </code></pre> <p>Sample:</p> <pre><code>transactions = pd.DataFrame({'customer_id':[1,2,3,1,2,1], 'Month': [4,5,6,1,1,3]}) print (transactions) Month customer_id 0 4 1 1 5 2 2 6 3 3 1 1 4 1 2 5 3 1 df = transactions.groupby('customer_id').aggregate({ 'Month' : ['min', 'max']}) print (df) Month min max customer_id 1 1 4 2 1 5 3 6 6 </code></pre> <p>Faster solution is:</p> <pre><code>g = transactions.groupby('customer_id')['Month'] print (pd.concat([g.min(), g.max()], axis=1, keys=['min','max'])) </code></pre>
1
2016-07-29T07:13:58Z
[ "python", "pandas" ]
IPython 5.0: Remove spaces between input lines
38,652,671
<p>(This question is essentially <a href="http://stackoverflow.com/questions/2351857/ipython-single-line-spacing-possible">this question</a>, but for IPython version 5.0)</p> <p>I'd like to have a classic prompt with IPython 5.0.</p> <p><a href="http://stackoverflow.com/questions/38275585/adding-color-to-new-style-ipython-v5-prompt">This</a> question helps customize my prompt. In fact, I discovered that IPython has a class definition for the <a href="http://ipython.readthedocs.io/en/latest/api/generated/IPython.terminal.prompts.html#IPython.terminal.prompts.ClassicPrompts" rel="nofollow"><code>ClassicPrompts</code></a> already.</p> <p>All I need to do is to put the following in a file called <code>00-classic-prompts.py</code> or some such in <code>~/.ipython/profile_default/startup/</code>:</p> <pre><code>from IPython.terminal.prompts import ClassicPrompts ip = get_ipython() ip.prompts = ClassicPrompts(ip) </code></pre> <p>But different prompt lines still render as:</p> <pre><code>&gt;&gt;&gt; print('Hello world!') Hello world! &gt;&gt;&gt; </code></pre> <p>With an extra new-line before every input prompt. How can I remove this?</p>
1
2016-07-29T07:14:23Z
38,667,776
<p>Please append this line on the bottom of your existing startup script:</p> <pre><code>ip.separate_in = '' </code></pre> <p>This is a <a href="http://ipython.readthedocs.io/en/latest/config/options/terminal.html" rel="nofollow">documented feature</a> but currently has no description, making it hard-to-find.</p>
2
2016-07-29T21:31:21Z
[ "python", "ipython", "prompt" ]
Counting repeated blocks in pandas
38,652,683
<p>I have the following dataframe and I am trying to label an entire block with a number which is based on how many similar blocks has been seen upto now based on class column. Consecutive class value is given the same number. If the same class block comes later, the number will be incremented. If some new class block comes, then it is initialized to <code>1</code>.</p> <pre><code>df = DataFrame(zip(range(10,30), range(20)), columns = ['a','b']) df['Class'] = [np.nan, np.nan, np.nan, np.nan, 'a', 'a', 'a', 'a', np.nan, np.nan,'a', 'a', 'a', 'a', 'a', np.nan, np.nan, 'b', 'b','b'] a b Class 0 10 0 NaN 1 11 1 NaN 2 12 2 NaN 3 13 3 NaN 4 14 4 a 5 15 5 a 6 16 6 a 7 17 7 a 8 18 8 NaN 9 19 9 NaN 10 20 10 a 11 21 11 a 12 22 12 a 13 23 13 a 14 24 14 a 15 25 15 NaN 16 26 16 NaN 17 27 17 b 18 28 18 b 19 29 19 b </code></pre> <p>Sample output looks like this:</p> <pre><code> a b Class block_encounter_no 0 10 0 NaN NaN 1 11 1 NaN NaN 2 12 2 NaN NaN 3 13 3 NaN NaN 4 14 4 a 1 5 15 5 a 1 6 16 6 a 1 7 17 7 a 1 8 18 8 NaN NaN 9 19 9 NaN NaN 10 20 10 a 2 11 21 11 a 2 12 22 12 a 2 13 23 13 a 2 14 24 14 a 2 15 25 15 NaN NaN 16 26 16 NaN NaN 17 27 17 b 1 18 28 18 b 1 19 29 19 b 1 </code></pre>
2
2016-07-29T07:14:52Z
38,653,230
<p>Do this:</p> <pre><code>df['block_encounter_no'] = \ np.where(df.Class.notnull(), (df.Class.notnull() &amp; (df.Class != df.Class.shift())).cumsum(), np.nan) </code></pre> <p><a href="http://i.stack.imgur.com/yz61E.png" rel="nofollow"><img src="http://i.stack.imgur.com/yz61E.png" alt="enter image description here"></a></p>
1
2016-07-29T07:45:42Z
[ "python", "pandas", "dataframe", null, "cumsum" ]
Counting repeated blocks in pandas
38,652,683
<p>I have the following dataframe and I am trying to label an entire block with a number which is based on how many similar blocks has been seen upto now based on class column. Consecutive class value is given the same number. If the same class block comes later, the number will be incremented. If some new class block comes, then it is initialized to <code>1</code>.</p> <pre><code>df = DataFrame(zip(range(10,30), range(20)), columns = ['a','b']) df['Class'] = [np.nan, np.nan, np.nan, np.nan, 'a', 'a', 'a', 'a', np.nan, np.nan,'a', 'a', 'a', 'a', 'a', np.nan, np.nan, 'b', 'b','b'] a b Class 0 10 0 NaN 1 11 1 NaN 2 12 2 NaN 3 13 3 NaN 4 14 4 a 5 15 5 a 6 16 6 a 7 17 7 a 8 18 8 NaN 9 19 9 NaN 10 20 10 a 11 21 11 a 12 22 12 a 13 23 13 a 14 24 14 a 15 25 15 NaN 16 26 16 NaN 17 27 17 b 18 28 18 b 19 29 19 b </code></pre> <p>Sample output looks like this:</p> <pre><code> a b Class block_encounter_no 0 10 0 NaN NaN 1 11 1 NaN NaN 2 12 2 NaN NaN 3 13 3 NaN NaN 4 14 4 a 1 5 15 5 a 1 6 16 6 a 1 7 17 7 a 1 8 18 8 NaN NaN 9 19 9 NaN NaN 10 20 10 a 2 11 21 11 a 2 12 22 12 a 2 13 23 13 a 2 14 24 14 a 2 15 25 15 NaN NaN 16 26 16 NaN NaN 17 27 17 b 1 18 28 18 b 1 19 29 19 b 1 </code></pre>
2
2016-07-29T07:14:52Z
38,653,657
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a>:</p> <pre><code>df['block_encounter_no'] = (df.Class != df.Class.shift()).mask(df.Class.isnull()) .groupby(df.Class).cumsum() print (df) a b Class block_encounter_no 0 10 0 NaN NaN 1 11 1 NaN NaN 2 12 2 NaN NaN 3 13 3 NaN NaN 4 14 4 a 1.0 5 15 5 a 1.0 6 16 6 a 1.0 7 17 7 a 1.0 8 18 8 NaN NaN 9 19 9 NaN NaN 10 20 10 a 2.0 11 21 11 a 2.0 12 22 12 a 2.0 13 23 13 a 2.0 14 24 14 a 2.0 15 25 15 NaN NaN 16 26 16 NaN NaN 17 27 17 b 1.0 18 28 18 b 1.0 19 29 19 b 1.0 </code></pre>
2
2016-07-29T08:06:56Z
[ "python", "pandas", "dataframe", null, "cumsum" ]
Concatenate strings together in template if statement
38,652,701
<p>I read <a href="http://stackoverflow.com/questions/7665514/django-highlight-navigation-based-on-current-page">this</a> and my code looked like this:</p> <p>html: </p> <pre><code>&lt;li {% if request.path == '/groups/{{ group.id }}/' %}class="active"{% endif %} &gt;&lt;a href="{% url 'detail' group.id %}"&gt;Link&lt;/a&gt;&lt;/li&gt; </code></pre> <p>The only problem is that <code>/groups/{{ group.id }}/</code> obviously turn into:</p> <p><code>/groups/{{ group.id }}/</code> </p> <p>not</p> <p><code>/groups/1/</code></p> <p><a href="http://stackoverflow.com/questions/4386168/how-to-concatenate-strings-in-django-templates">that</a> will end up being a lot of code if type it for the other 10 links on the page.</p>
1
2016-07-29T07:15:50Z
38,652,776
<p>Instead of hardcoding the url, use the <code>url</code> tag with <code>as</code></p> <pre><code>{% url 'my_group_url_name' group.id as group_url %} {% if request.path == group_url %} </code></pre>
4
2016-07-29T07:19:53Z
[ "python", "django" ]
From concurrent.futures to asyncio
38,652,819
<p>I have two problems with <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow">concurrent.futures</a>:</p> <h1>How to break time.sleep() in a python concurrent.futures?</h1> <p>Conclusion: time.sleep() cannot be interrupted. One solution is: You can write a loop around it and do short sleeps.</p> <p>See <a href="http://stackoverflow.com/questions/38461603/how-to-break-time-sleep-in-a-python-concurrent-futures">How to break time.sleep() in a python concurrent.futures</a></p> <h1>Individual timeouts for concurrent.futures?</h1> <p>Conclusion: individual timeouts need to implemented by the user. For example: for each timeout you can call to <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.wait" rel="nofollow">wait()</a>.</p> <p>See <a href="http://stackoverflow.com/questions/38456357/individual-timeouts-for-concurrent-futures">Individual timeouts for concurrent.futures</a></p> <h1>Question</h1> <p>Does <a href="https://docs.python.org/3/library/asyncio.html" rel="nofollow">asyncio</a> solve theses problems?</p>
4
2016-07-29T07:22:15Z
38,655,063
<p>In the asyncio model, execution is scheduled and coordinated by an event loop. To cancel execution of a currently suspended task, you essentially simply have to <em>not resume</em> it. While this works a little different in practice, it should be obvious that this makes cancelling a suspended task simple in theory.</p> <p>Individual timeouts are certainly possible the same way: whenever you suspend a coroutine to wait for a result, you want to supply a timeout value. The event loop will ensure to cancel the waiting task when that timeout is reached and the task hasn't completed yet.</p> <p>Some concrete samples:</p> <pre><code>&gt;&gt;&gt; import asyncio &gt;&gt;&gt; loop = asyncio.get_event_loop() &gt;&gt;&gt; task = asyncio.ensure_future(asyncio.sleep(5)) &gt;&gt;&gt; task.cancel() &gt;&gt;&gt; loop.run_until_complete(task) Traceback (most recent call last): ... concurrent.futures._base.CancelledError </code></pre> <p>In practice, this might be implemented using something like this:</p> <pre><code>class Foo: task = None async def sleeper(self): self.task = asyncio.sleep(60) try: await self.task except concurrent.futures.CancelledError: raise NotImplementedError </code></pre> <p>While this method is asleep, somebody else can call <code>foo.task.cancel()</code> to wake up the coroutine and let it handle the cancellation. Alternatively whoever calls <code>sleeper()</code> can cancel <em>it</em> directly without giving it a chance to clean up.</p> <p>Setting timeouts is similarly easy:</p> <pre><code>&gt;&gt;&gt; loop.run_until_complete(asyncio.wait_for(asyncio.sleep(60), 5)) [ ... 5 seconds later ... ] Traceback (most recent call last): ... concurrent.futures._base.TimeoutError </code></pre> <p>Particularly in the context of HTTP request timeouts, see <a href="http://aiohttp.readthedocs.io" rel="nofollow">aiohttp</a>:</p> <pre><code>async def fetch_page(session, url): with aiohttp.Timeout(10): async with session.get(url) as response: assert response.status == 200 return await response.read() with aiohttp.ClientSession(loop=loop) as session: content = loop.run_until_complete(fetch_page(session, 'http://python.org')) </code></pre> <p>Obviously each call to <code>fetch_page</code> can decide on its own <code>aiohttp.Timeout</code> value, and each individual instance will throw its own exception when that timeout is reached.</p>
3
2016-07-29T09:19:44Z
[ "python", "python-multiprocessing", "python-asyncio", "concurrent.futures" ]
Pivoting data in pandas
38,652,881
<p>Suppose I have the following data as a pandas dataframe:</p> <pre><code> type exdiv paydate amount declared 2014-01-31 final 2014-03-03 2014-03-10 3.10 2014-06-27 interim 2014-08-11 2014-08-18 1.55 2015-01-30 final 2015-03-02 2015-03-09 2.33 2015-01-30 final 2015-03-02 2015-03-09 0.77 2015-06-26 interim 2015-08-07 2015-08-17 1.80 2016-01-29 final 2016-02-29 2016-03-07 3.45 </code></pre> <p>The 2015-01-30 entry is repeated twice. What is the easiest way to sum up that row so that I only have one entry equal to 3.10 for 2015-01-30?</p> <p>I've tried the following so far:</p> <pre><code>x=pd.pivot_table(df, values='amount', index=['exdiv','paydate','type'], columns=[]) </code></pre> <p>But this creates a multi-index and I can't use the current index column ('declared'). </p> <p>I know I can add the index as a normal column, run the command and try to convert the multi-index back to a single index, but I'm sure there must be a better method in pandas?</p>
1
2016-07-29T07:25:34Z
38,653,022
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>:</p> <pre><code>df['amount'] = df.groupby(level=0)['amount'].transform(sum) df = df.reset_index().drop_duplicates(subset=['declared','type','exdiv','paydate']) print (df) declared type exdiv paydate amount 0 2014-01-31 final 2014-03-03 2014-03-10 3.10 1 2014-06-27 interim 2014-08-11 2014-08-18 1.55 2 2015-01-30 final 2015-03-02 2015-03-09 3.10 4 2015-06-26 interim 2015-08-07 2015-08-17 1.80 5 2016-01-29 final 2016-02-29 2016-03-07 3.45 </code></pre> <p>Or add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and <code>aggfunc=sum</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>x=pd.pivot_table(df.reset_index(), values='amount', index=['declared','exdiv','paydate','type'], aggfunc=sum).reset_index() print (x) declared exdiv paydate type amount 0 2014-01-31 2014-03-03 2014-03-10 final 3.10 1 2014-06-27 2014-08-11 2014-08-18 interim 1.55 2 2015-01-30 2015-03-02 2015-03-09 final 3.10 3 2015-06-26 2015-08-07 2015-08-17 interim 1.80 4 2016-01-29 2016-02-29 2016-03-07 final 3.45 </code></pre>
2
2016-07-29T07:32:40Z
[ "python", "pandas" ]
How to retrieve <th><td> using Beautifulsoup
38,652,893
<p>I am using Python 3 on Windows 7.</p> <p>However, I am unable to download some of the data listed in the web site as follows:</p> <p><a href="http://data.tsci.com.cn/stock/00939/STK_Broker.htm" rel="nofollow">http://data.tsci.com.cn/stock/00939/STK_Broker.htm</a></p> <p>453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 7387.花旗环球 52.72M 9.84M 2.32 5.36</p> <p>When I use Google Chrome and use 'View Page Source', the data does not show up at all. However, when I use 'Inspect', I can able to read the data.</p> <pre><code>'&lt;th&gt;1453.IMC&lt;/th&gt;' '&lt;td&gt;98.28M&lt;/td&gt;' '&lt;td&gt;18.44M&lt;/td&gt;' '&lt;td&gt;4.32&lt;/td&gt;' '&lt;td&gt;5.33&lt;/td&gt;' '&lt;th&gt;1499.Optiver &lt;/th&gt;' '&lt;td&gt; 70.91M&lt;/td&gt;' '&lt;td&gt;13.29M &lt;/td&gt;' '&lt;td&gt;3.12&lt;/td&gt;' '&lt;td&gt;5.34&lt;/td&gt;' </code></pre> <p>Please kindly explain to me if the data is hide in CSS Style sheet or is there any way to retrieve the data listed.</p> <p>Thank you</p> <p>Regards, Crusier</p> <pre><code>from bs4 import BeautifulSoup import urllib import requests stock_code = ('00939', '0001') def web_scraper(stock_code): broker_url = 'http://data.tsci.com.cn/stock/' end_url = '/STK_Broker.htm' for code in stock_code: new_url = broker_url + code + end_url response = requests.get(new_url) html = response.content soup = BeautifulSoup(html, "html.parser") Buylist = soup.find_all('div', id ="BuyingSeats") Selllist = soup.find_all('div', id ="SellSeats") print(Buylist) print(Selllist) web_scraper(stock_code) </code></pre>
1
2016-07-29T07:26:04Z
38,653,558
<p>as someone already mentioned, Selenium is the way to go.</p> <pre><code>from selenium import webdriver broker_url = 'http://data.tsci.com.cn/stock/00939/STK_Broker.htm' mydriver = webdriver.Chrome() mydriver.get(broker_url) BuyList = mydriver.find_element_by_css_selector('#Buylist') rows = BuyList.find_elements_by_tag_name('tr') for row in rows: print(row.text) </code></pre>
0
2016-07-29T08:02:08Z
[ "python", "beautifulsoup" ]
How to retrieve <th><td> using Beautifulsoup
38,652,893
<p>I am using Python 3 on Windows 7.</p> <p>However, I am unable to download some of the data listed in the web site as follows:</p> <p><a href="http://data.tsci.com.cn/stock/00939/STK_Broker.htm" rel="nofollow">http://data.tsci.com.cn/stock/00939/STK_Broker.htm</a></p> <p>453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 7387.花旗环球 52.72M 9.84M 2.32 5.36</p> <p>When I use Google Chrome and use 'View Page Source', the data does not show up at all. However, when I use 'Inspect', I can able to read the data.</p> <pre><code>'&lt;th&gt;1453.IMC&lt;/th&gt;' '&lt;td&gt;98.28M&lt;/td&gt;' '&lt;td&gt;18.44M&lt;/td&gt;' '&lt;td&gt;4.32&lt;/td&gt;' '&lt;td&gt;5.33&lt;/td&gt;' '&lt;th&gt;1499.Optiver &lt;/th&gt;' '&lt;td&gt; 70.91M&lt;/td&gt;' '&lt;td&gt;13.29M &lt;/td&gt;' '&lt;td&gt;3.12&lt;/td&gt;' '&lt;td&gt;5.34&lt;/td&gt;' </code></pre> <p>Please kindly explain to me if the data is hide in CSS Style sheet or is there any way to retrieve the data listed.</p> <p>Thank you</p> <p>Regards, Crusier</p> <pre><code>from bs4 import BeautifulSoup import urllib import requests stock_code = ('00939', '0001') def web_scraper(stock_code): broker_url = 'http://data.tsci.com.cn/stock/' end_url = '/STK_Broker.htm' for code in stock_code: new_url = broker_url + code + end_url response = requests.get(new_url) html = response.content soup = BeautifulSoup(html, "html.parser") Buylist = soup.find_all('div', id ="BuyingSeats") Selllist = soup.find_all('div', id ="SellSeats") print(Buylist) print(Selllist) web_scraper(stock_code) </code></pre>
1
2016-07-29T07:26:04Z
38,653,572
<p>The data is dynamically generated but you can mimic an ajax request and get it in json format:</p> <pre><code>import requests params = {"Code": "E00939", "PkgType": "11036", "val": "50"} js = requests.get("http://data.tsci.com.cn/RDS.aspx", params=params).json() print(js) </code></pre> <p>That gives you the table data like:</p> <pre><code>{u'BrokerBuy': [{u'AV': u'5.24', u'BrokerNo': u'Optiver', u'percent': u'10.09', u'shares': u'43.06M', u'turnover': u'225.67M'}, {u'AV': u'5.26', u'BrokerNo': u'UBS HK', u'percent': u'4.81', u'shares': u'20.47M', u'turnover': u'107.63M'}, {u'AV': u'5.22', u'BrokerNo': u'\u4e2d\u94f6\u56fd\u9645', u'percent': u'4.63', u'shares': u'19.83M', u'turnover': u'103.51M'}, {u'AV': u'5.25', u'BrokerNo': u'\u745e\u4fe1', u'percent': u'3.88', u'shares': u'16.54M', u'turnover': u'86.82M'}, {u'AV': u'5.24', u'BrokerNo': u'IMC', u'percent': u'3.84', u'shares': u'16.38M', u'turnover': u'85.89M'}], u'BrokerSell': [{u'AV': u'5.21', u'BrokerNo': u'\u4e2d\u6295\u4fe1\u606f', u'percent': u'8.90', u'shares': u'38.19M', u'turnover': u'199.12M'}, {u'AV': u'5.24', u'BrokerNo': u'Optiver', u'percent': u'5.51', u'shares': u'23.55M', u'turnover': u'123.29M'}, {u'AV': u'5.24', u'BrokerNo': u'\u9ad8\u76db\u4e9a\u6d32', u'percent': u'4.43', u'shares': u'18.91M', u'turnover': u'99.19M'}, {u'AV': u'5.28', u'BrokerNo': u'JPMorgan', u'percent': u'2.28', u'shares': u'9.67M', u'turnover': u'51.09M'}, {u'AV': u'5.25', u'BrokerNo': u'IMC', u'percent': u'0.88', u'shares': u'3.76M', u'turnover': u'19.70M'}], u'Buy': [{u'AV': u'5.24', u'BrokerNo': u'1499.Optiver', u'percent': u'10.09', u'shares': u'43.06M', u'turnover': u'225.67M'}, {u'AV': u'5.24', u'BrokerNo': u'1453.IMC', u'percent': u'3.84', u'shares': u'16.38M', u'turnover': u'85.89M'}, {u'AV': u'5.24', u'BrokerNo': u'7387.\u82b1\u65d7\u73af\u7403', u'percent': u'3.08', u'shares': u'13.16M', u'turnover': u'68.97M'}, {u'AV': u'5.23', u'BrokerNo': u'6698.\u76c8\u900f\u8bc1\u5238', u'percent': u'1.74', u'shares': u'7.43M', u'turnover': u'38.86M'}, {u'AV': u'5.21', u'BrokerNo': u'1799.\u8000\u624d\u8bc1\u5238', u'percent': u'1.44', u'shares': u'6.18M', u'turnover': u'32.16M'}], u'NetBuy': [{u'AV': u'5.25', u'BrokerNo': u'1499.Optiver', u'percent': u'4.58', u'shares': u'19.51M', u'turnover': u'102.37M'}, {u'AV': u'5.24', u'BrokerNo': u'1453.IMC', u'percent': u'2.96', u'shares': u'12.62M', u'turnover': u'66.19M'}, {u'AV': u'5.24', u'BrokerNo': u'7387.\u82b1\u65d7\u73af\u7403', u'percent': u'2.81', u'shares': u'11.98M', u'turnover': u'62.78M'}, {u'AV': u'5.23', u'BrokerNo': u'6698.\u76c8\u900f\u8bc1\u5238', u'percent': u'1.66', u'shares': u'7.12M', u'turnover': u'37.24M'}, {u'AV': u'5.26', u'BrokerNo': u'9065.UBS HK', u'percent': u'1.39', u'shares': u'5.91M', u'turnover': u'31.11M'}], u'NetNameBuy': [{u'AV': u'5.26', u'BrokerNo': u'UBS HK', u'percent': u'4.58', u'shares': u'19.49M', u'turnover': u'102.44M'}, {u'AV': u'5.25', u'BrokerNo': u'Optiver', u'percent': u'4.58', u'shares': u'19.51M', u'turnover': u'102.37M'}, {u'AV': u'5.22', u'BrokerNo': u'\u4e2d\u94f6\u56fd\u9645', u'percent': u'4.28', u'shares': u'18.37M', u'turnover': u'95.84M'}, {u'AV': u'5.24', u'BrokerNo': u'\u745e\u4fe1', u'percent': u'3.16', u'shares': u'13.49M', u'turnover': u'70.68M'}, {u'AV': u'5.24', u'BrokerNo': u'IMC', u'percent': u'2.96', u'shares': u'12.62M', u'turnover': u'66.19M'}], u'NetNameSell': [{u'AV': u'5.29', u'BrokerNo': u'\u5174\u4e1a\u91d1\u878d', u'percent': u'0.37', u'shares': u'1.58M', u'turnover': u'8.36M'}, {u'AV': u'5.25', u'BrokerNo': u'\u4e2d\u56fd\u91d1\u878d', u'percent': u'0.16', u'shares': u'696K', u'turnover': u'3.65M'}, {u'AV': u'5.32', u'BrokerNo': u'\u94f6\u6cb3\u56fd\u9645', u'percent': u'0.16', u'shares': u'671K', u'turnover': u'3.57M'}, {u'AV': u'5.29', u'BrokerNo': u'Penjing', u'percent': u'0.07', u'shares': u'300K', u'turnover': u'1.59M'}, {u'AV': u'5.31', u'BrokerNo': u'\u5efa\u94f6\u56fd\u9645', u'percent': u'0.06', u'shares': u'272K', u'turnover': u'1.44M'}], u'NetSell': [{u'AV': u'5.21', u'BrokerNo': u'6999.\u4e2d\u6295\u4fe1\u606f', u'percent': u'8.61', u'shares': u'36.93M', u'turnover': u'192.59M'}, {u'AV': u'5.24', u'BrokerNo': u'3440.\u9ad8\u76db\u4e9a\u6d32', u'percent': u'4.03', u'shares': u'17.20M', u'turnover': u'90.15M'}, {u'AV': u'5.30', u'BrokerNo': u'5337.JPMorgan', u'percent': u'0.67', u'shares': u'2.83M', u'turnover': u'15.00M'}, {u'AV': u'5.29', u'BrokerNo': u'5980.\u5174\u4e1a\u91d1\u878d', u'percent': u'0.37', u'shares': u'1.58M', u'turnover': u'8.36M'}, {u'AV': u'5.30', u'BrokerNo': u'8738.\u6c47\u4e30\u8bc1\u5238', u'percent': u'0.36', u'shares': u'1.53M', u'turnover': u'8.10M'}], u'Sell': [{u'AV': u'5.21', u'BrokerNo': u'6999.\u4e2d\u6295\u4fe1\u606f', u'percent': u'8.90', u'shares': u'38.19M', u'turnover': u'199.12M'}, {u'AV': u'5.24', u'BrokerNo': u'1499.Optiver', u'percent': u'5.51', u'shares': u'23.55M', u'turnover': u'123.29M'}, {u'AV': u'5.24', u'BrokerNo': u'3440.\u9ad8\u76db\u4e9a\u6d32', u'percent': u'4.19', u'shares': u'17.89M', u'turnover': u'93.75M'}, {u'AV': u'5.25', u'BrokerNo': u'1453.IMC', u'percent': u'0.88', u'shares': u'3.76M', u'turnover': u'19.70M'}, {u'AV': u'5.30', u'BrokerNo': u'5337.JPMorgan', u'percent': u'0.70', u'shares': u'2.96M', u'turnover': u'15.66M'}], u'Total': {u'In': u'1.26B', u'Net': u'5.800971E+08', u'Out': u'682.58M', u'right': u'98.71'}} </code></pre> <p>Which has all the table data, it is just a matter of using the keys to access what you need.</p> <p>So in your loop, just pass each code:</p> <pre><code>for code in stock_code: params["Code"] = "E{}".format(code) js = requests.get("http://data.tsci.com.cn/RDS.aspx", params=params).json() </code></pre> <p>One thing to note, <code>0001</code> does not work here nor in your broswer, what does work is <code>00001</code>.</p>
0
2016-07-29T08:02:40Z
[ "python", "beautifulsoup" ]
Python 3.4 Logging Configuration
38,652,992
<p>I am trying to convert my current projects from python 2.7 to 3.5. One of the first tasks is configuration of logging. I use a configuration file for flexibility and the date is part of the file name. Below is the code for setting up the file handler that works fine in 2.7</p> <pre><code>[handler_fileHandler] class=FileHandler level=DEBUG formatter=simpleFormatter # Only one log per day will be created. All messages will be appended to it. args=("D:\\Logs\\PyLogs\\" + time.strftime("%Y%m%d%H%M%S")+'.log', 'a') </code></pre> <p>In 3.5 the following error occurs:</p> <blockquote> <p>configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%Y%m%d%H%M%S")+\'.log\', \'a\')'</p> </blockquote> <p>Has anyone experience with this? Is there a better way to format the date within the configuration file?</p>
0
2016-07-29T07:30:54Z
38,656,407
<p>similar subject as this post: <a href="http://stackoverflow.com/questions/14340366/configparser-and-string-with">Configparser and string with %</a></p> <p>I think you may need the substitution for %</p>
1
2016-07-29T10:21:40Z
[ "python", "python-3.x", "python2to3" ]
How to interpret (read) signed 24bits data from 32bits
38,653,094
<p>I have raw file containing signed 24bits data packed into 32bits example:</p> <pre><code>00 4D 4A FF 00 FF FF FF </code></pre> <p>I would like read those data and get signed integer between [-2^23 and 2^23-1]</p> <p>for now I write </p> <pre><code> int32_1 = file1.read(4) val1 = (( unpack('=l', int32_1)[0] &amp; 0xFFFFFF00)&gt;&gt;8 </code></pre> <p>but how to take the 2-complement into account to interpret <code>00FFFFFF</code> as -1 ?</p>
1
2016-07-29T07:36:50Z
38,653,351
<p>you can shift 8 bits to the left, take the result as a signed 32bit integer (use ctypes library), and divide by 256</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; i = 0x00ffffff &gt;&gt;&gt; i 16777215 &gt;&gt;&gt; i&lt;&lt;8 4294967040 &gt;&gt;&gt; ctypes.c_int32(i&lt;&lt;8).value -256 &gt;&gt;&gt; ctypes.c_int32(i&lt;&lt;8).value//256 -1 </code></pre>
1
2016-07-29T07:51:46Z
[ "python" ]
How to interpret (read) signed 24bits data from 32bits
38,653,094
<p>I have raw file containing signed 24bits data packed into 32bits example:</p> <pre><code>00 4D 4A FF 00 FF FF FF </code></pre> <p>I would like read those data and get signed integer between [-2^23 and 2^23-1]</p> <p>for now I write </p> <pre><code> int32_1 = file1.read(4) val1 = (( unpack('=l', int32_1)[0] &amp; 0xFFFFFF00)&gt;&gt;8 </code></pre> <p>but how to take the 2-complement into account to interpret <code>00FFFFFF</code> as -1 ?</p>
1
2016-07-29T07:36:50Z
38,654,783
<p>Your code is making things more complicated than they need to be. However, you really should specify the endian type correctly in the <code>unpack</code> format string.</p> <pre><code>from binascii import hexlify from struct import unpack data = ('\x00\x03\x02\x01', '\x00\x4D\x4A\xFF', '\x00\xFF\xFF\xFF') for b in data: i = unpack('&lt;l', b)[0] &gt;&gt; 8 print hexlify(b), i </code></pre> <p><strong>output</strong></p> <pre><code>00030201 66051 004d4aff -46515 00ffffff -1 </code></pre> <hr> <p>FWIW, here's a version that works in Python 3 or Python 2; the output is slightly different in Python 3, since normal strings in Python 3 are Unicode; byte strings are "special".</p> <pre><code>from __future__ import print_function from binascii import hexlify from struct import unpack data = (b'\x00\x03\x02\x01', b'\x00\x4D\x4A\xFF', b'\x00\xFF\xFF\xFF') for b in data: i = unpack('&lt;l', b)[0] &gt;&gt; 8 print(hexlify(b), i) </code></pre> <p><strong>Python 3 output</strong></p> <pre><code>b'00030201' 66051 b'004d4aff' -46515 b'00ffffff' -1 </code></pre> <p>And here's a version that only runs on Python 3:</p> <pre><code>from binascii import hexlify data = (b'\x00\x03\x02\x01', b'\x00\x4D\x4A\xFF', b'\x00\xFF\xFF\xFF') for b in data: i = int.from_bytes(b[1:], 'little', signed=True) print(hexlify(b), i) </code></pre>
2
2016-07-29T09:05:03Z
[ "python" ]
Straightforward solution on how to stereo calibration and rectifications OpenCV?
38,653,354
<p>I have been digging on this topic for almost a week and couldn't find any solid solution yet. It is interesting that no one ever posted a <strong>straightforward</strong> solution on how to calibrate and rectify a stereo camera with OpenCV in order to compute the depth, from here and there(<a href="http://stackoverflow.com/questions/28222763/stereo-calibration-opencv-python-and-disparity-map">this</a> for calibration and <a href="http://vgg.fiit.stuba.sk/2015-02/2783/" rel="nofollow">this</a> for rectification, the codes posted are not quite integrated though) I have come up with the following code snap, BUT it does not rectify the image OK!!</p> <pre><code>import numpy as np import cv2 import glob # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((6*9,3), np.float32) objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = {} # 3d point in real world space imgpoints = {} # 2d points in image plane. # calibrate stereo for side in ['left', 'right']: counter = 0 images = glob.glob('images/%s*.jpg' %side) objpoints[side] = []; imgpoints[side] = []; for fname in images: img = cv2.imread(fname) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (9,6),None) # If found, add object points, image points (after refining them) if ret == True: objpoints[side].append(objp) cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) imgpoints[side].append(corners) counter += 1 assert counter == len(images), "missed chessboard!!" stereocalib_criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) stereocalib_flags = cv2.CALIB_FIX_ASPECT_RATIO | cv2.CALIB_ZERO_TANGENT_DIST | cv2.CALIB_SAME_FOCAL_LENGTH | cv2.CALIB_RATIONAL_MODEL | cv2.CALIB_FIX_K3 | cv2.CALIB_FIX_K4 | cv2.CALIB_FIX_K5 retval,cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, R, T, E, F = cv2.stereoCalibrate(objpoints['left'], imgpoints['left'], imgpoints['right'], (640, 480), criteria = stereocalib_criteria, flags = stereocalib_flags) rectify_scale = 0.1 # 0=full crop, 1=no crop R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, (640, 480), R, T, alpha = rectify_scale) left_maps = cv2.initUndistortRectifyMap(cameraMatrix1, distCoeffs1, R1, P1, (640, 480), cv2.CV_16SC2) right_maps = cv2.initUndistortRectifyMap(cameraMatrix2, distCoeffs2, R2, P2, (640, 480), cv2.CV_16SC2) # Assuming you have left01.jpg and right01.jpg that you want to rectify lFrame = cv2.imread('images/left01.jpg') rFrame = cv2.imread('images/right01.jpg') left_img_remap = cv2.remap(lFrame, left_maps[0], left_maps[1], cv2.INTER_LANCZOS4) right_img_remap = cv2.remap(rFrame, right_maps[0], right_maps[1], cv2.INTER_LANCZOS4) for line in range(0, int(right_img_remap.shape[0] / 20)): left_img_remap[line * 20, :] = (0, 0, 255) right_img_remap[line * 20, :] = (0, 0, 255) cv2.imshow('winname', np.hstack([left_img_remap, right_img_remap])) cv2.waitKey(0) exit(0) </code></pre> <p>The output of the above is the image below <a href="http://i.stack.imgur.com/H0oYt.png" rel="nofollow"><img src="http://i.stack.imgur.com/H0oYt.png" alt="enter image description here"></a></p> <p>As you can see the images are not rectified!!</p> <h3>Question:</h3> <ul> <li>What is wrong with the code?</li> </ul>
0
2016-07-29T07:51:57Z
38,673,008
<p>I couldn't find what was the thing I did wrong which led to incorrect answers, but for what it worth I have found a solution that does rectify OK and more!!<br /> I came across the <a href="https://github.com/erget/StereoVision" rel="nofollow">StereoVision</a> library and considering the low documentation level it has, I have managed to fetch/write the following snaps which calibrate and rectifies OK.</p> <pre><code>import cv2 import os.path import numpy as np from stereovision.calibration import StereoCalibrator, StereoCalibration from stereovision.blockmatchers import StereoBM, StereoSGBM calib_dir = 'data/config/calibration' if(not os.path.exists(calib_dir)): calibrator = StereoCalibrator(9, 6, 2, (480, 640)) for idx in range(1, 14): calibrator.add_corners((cv2.imread('images/left%02d.jpg' %idx), cv2.imread('images/right%02d.jpg' %idx))) calibration = calibrator.calibrate_cameras() print "Calibation error:", calibrator.check_calibration(calibration) calibration.export(calib_dir) calibration = StereoCalibration(input_folder=calib_dir) if True: block_matcher = StereoBM() else: block_matcher = StereoSGBM() for idx in range(1, 14): image_pair = (cv2.imread('images/left%02d.jpg' %idx), cv2.imread('images/right%02d.jpg' %idx)) rectified_pair = calibration.rectify(image_pair) disparity = block_matcher.get_disparity(rectified_pair) norm_coeff = 255 / disparity.max() cv2.imshow('Disparity %02d' %idx, disparity * norm_coeff / 255) for line in range(0, int(rectified_pair[0].shape[0] / 20)): rectified_pair[0][line * 20, :] = (0, 0, 255) rectified_pair[1][line * 20, :] = (0, 0, 255) cv2.imshow('Rect %02d' %idx, np.hstack(rectified_pair)) cv2.waitKey() </code></pre> <p>The following is the result of rectification of the same image I have posted in my question. <a href="http://i.stack.imgur.com/h0azF.png" rel="nofollow"><img src="http://i.stack.imgur.com/h0azF.png" alt="enter image description here"></a> Although for computing the disparity map It needs its parameters to be tuned(a tool is provided by the package) but it will do the job :) </p>
0
2016-07-30T10:46:31Z
[ "python", "opencv", "image-processing", "video-processing" ]
Large Scenario Outline tables without having to explicitly mention all parameters in the step definitons
38,653,356
<p>In Python's <a href="https://pythonhosted.org/behave/index.html" rel="nofollow">behave</a> library, I can write a feature file with a parametrised Scenario Outline like so (adapted from <a href="https://jenisys.github.io/behave.example/tutorials/tutorial04.html" rel="nofollow">this tutorial</a>):</p> <pre><code># feature file Feature: Scenario Outline Example Scenario Outline: Use Blender with &lt;thing&gt; Given I put "&lt;thing&gt;" in a blender When I switch the blender on Then it should transform into "&lt;other thing&gt;" Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | | apples | apple juice | </code></pre> <p>The according step definitions would look like this:</p> <pre><code># steps file from behave import given, when, then from hamcrest import assert_that, equal_to from blender import Blender @given('I put "{thing}" in a blender') def step_given_put_thing_into_blender(context, thing): context.blender = Blender() context.blender.add(thing) @when('I switch the blender on') def step_when_switch_blender_on(context): context.blender.switch_on() @then('it should transform into "{other_thing}"') def step_then_should_transform_into(context, other_thing): assert_that(context.blender.result, equal_to(other_thing)) </code></pre> <p>As one can see, the way to pass the parameters from the feature file into the step functions is</p> <ul> <li>by explicitly mentioning them in the feature file enclosed in angle brackets </li> <li>then include the same words enclosed in curly brackets (why not angle brackets again?!) in the decorator of the step function</li> <li>and finally insert these words as function arguments of the step function.</li> </ul> <p>However, given a larger example table with a lot of columns, this quickly gets annoying to write and read:</p> <pre><code># feature file Feature: Large Table Example Scenario Outline: Use Blender with a lot of things Given I put "&lt;first_thing&gt;", "&lt;second_thing&gt;", "&lt;third_thing&gt;", "&lt;fourth_thing&gt;", "&lt;fifth_thing&gt;", "&lt;sixth_thing&gt;", "&lt;seventh_thing&gt;" in a blender When I switch the blender on Then it should transform into "&lt;other thing&gt;" Examples: Things | first thing | second thing | third thing | fourth thing | fifth thing | sixth thing | seventh thing | | a | b | c | d | e | f | g | h | | i | j | k | l | m | n | o | p | # steps file @given('I put "{first_thing}", "{second_thing}", "{third_thing}", "{fourth_thing}", "{fifth_thing}", "{sixth_thing}", "{seventh_thing}", in a blender') def step_given_put_thing_into_blender(context, first_thing, second_thing, third_thing, fourth_thing, fifth_thing, sixth_thing, seventh_thing): context.blender = Blender() context.blender.add(thing) ... </code></pre> <p>I think the point is clear. Is there any possibility to transfer the examples from a large table into the step definition without having to mention all of them explicitly? Are they, for instance, saved somewhere in the context variable even without mentioning them in the text (could not find them there yet)?</p>
1
2016-07-29T07:52:01Z
38,664,555
<p>The point is clear. </p> <p>Ask yourself why you <em>really</em> need all those variables?</p> <p>Are you trying to do too much in one scenario outline? Is it possible to split your problem in two?</p> <p>How would a scenario look like if you just implemented one of them, i.e. skipped the outline? Would it be large and cumbersome?</p> <p>Unfortunately, I don’t think your problem is that there are many parameter to mention. Your problem is that you are trying to use too many parameters. From where I sit, it looks like you are trying to do too much. Sorry.</p>
0
2016-07-29T17:38:04Z
[ "python", "gherkin", "python-behave" ]
Large Scenario Outline tables without having to explicitly mention all parameters in the step definitons
38,653,356
<p>In Python's <a href="https://pythonhosted.org/behave/index.html" rel="nofollow">behave</a> library, I can write a feature file with a parametrised Scenario Outline like so (adapted from <a href="https://jenisys.github.io/behave.example/tutorials/tutorial04.html" rel="nofollow">this tutorial</a>):</p> <pre><code># feature file Feature: Scenario Outline Example Scenario Outline: Use Blender with &lt;thing&gt; Given I put "&lt;thing&gt;" in a blender When I switch the blender on Then it should transform into "&lt;other thing&gt;" Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | | apples | apple juice | </code></pre> <p>The according step definitions would look like this:</p> <pre><code># steps file from behave import given, when, then from hamcrest import assert_that, equal_to from blender import Blender @given('I put "{thing}" in a blender') def step_given_put_thing_into_blender(context, thing): context.blender = Blender() context.blender.add(thing) @when('I switch the blender on') def step_when_switch_blender_on(context): context.blender.switch_on() @then('it should transform into "{other_thing}"') def step_then_should_transform_into(context, other_thing): assert_that(context.blender.result, equal_to(other_thing)) </code></pre> <p>As one can see, the way to pass the parameters from the feature file into the step functions is</p> <ul> <li>by explicitly mentioning them in the feature file enclosed in angle brackets </li> <li>then include the same words enclosed in curly brackets (why not angle brackets again?!) in the decorator of the step function</li> <li>and finally insert these words as function arguments of the step function.</li> </ul> <p>However, given a larger example table with a lot of columns, this quickly gets annoying to write and read:</p> <pre><code># feature file Feature: Large Table Example Scenario Outline: Use Blender with a lot of things Given I put "&lt;first_thing&gt;", "&lt;second_thing&gt;", "&lt;third_thing&gt;", "&lt;fourth_thing&gt;", "&lt;fifth_thing&gt;", "&lt;sixth_thing&gt;", "&lt;seventh_thing&gt;" in a blender When I switch the blender on Then it should transform into "&lt;other thing&gt;" Examples: Things | first thing | second thing | third thing | fourth thing | fifth thing | sixth thing | seventh thing | | a | b | c | d | e | f | g | h | | i | j | k | l | m | n | o | p | # steps file @given('I put "{first_thing}", "{second_thing}", "{third_thing}", "{fourth_thing}", "{fifth_thing}", "{sixth_thing}", "{seventh_thing}", in a blender') def step_given_put_thing_into_blender(context, first_thing, second_thing, third_thing, fourth_thing, fifth_thing, sixth_thing, seventh_thing): context.blender = Blender() context.blender.add(thing) ... </code></pre> <p>I think the point is clear. Is there any possibility to transfer the examples from a large table into the step definition without having to mention all of them explicitly? Are they, for instance, saved somewhere in the context variable even without mentioning them in the text (could not find them there yet)?</p>
1
2016-07-29T07:52:01Z
38,694,350
<p>Apart from considering if one really needs to work with large scenario outline tables (see the other answer), it is indeed possible to access the current table row without explicitly mentioning all parameters in the given/when/then step via <code>context.active_outline</code> <a href="https://pythonhosted.org/behave/context_attributes.html" rel="nofollow">(which is a bit hidden in the appendix of the documentation)</a>.</p> <p><code>context.active_outline</code> returns a <a href="https://pythonhosted.org/behave/api.html#behave.model.Row" rel="nofollow">behave.model.row</a> object which can be accessed in the following ways:</p> <ul> <li><code>context.active_outline.headings</code> returns a list of the table headers, no matter what the currently iterated row is (<em>first_thing</em>, <em>second_thing</em> etc. in the example from the question )</li> <li><code>context.active_outline.cells</code> returns a list of the cell values for the currently iterated row (<em>a</em>, <em>b</em>, <em>c</em> etc. in the example from the question)</li> <li>index-based access like <code>context.active_outline[0]</code> returns the cell value from the first column (no matter the heading) etc.</li> <li>named-based access like <code>context.active_outline['first_thing']</code> returns the cell value for the column with the <em>first_thing</em> header, no matter its index</li> </ul> <p>As <code>context.active_outline.headings</code> and <code>context.active_outline.cells</code> return lists, one can also do useful stuff like <code>for heading, cell in zip(context.active_outline.headings, context.active_outline.cells)</code> to iterate over the heading-value pairs etc.</p>
0
2016-08-01T08:36:51Z
[ "python", "gherkin", "python-behave" ]
python 2d array list index out of range
38,653,358
<pre><code>j=0 i=0 text=[[0 for x in range(5)]for y in range(2)] while (i&lt;5): for link in soup.findAll('td'): if j&lt;2: text[i][j]=link.string j+=1 i+=1 </code></pre> <p>The problem is I get the error message <code>list index out of range</code> but I already set the if condition so if <code>j</code> exceed <code>3</code> will nth happen. So what is the problem?</p>
-5
2016-07-29T07:52:09Z
38,653,461
<pre><code>[[0 for x in range(5)] for y in range(2)] </code></pre> <p>creates the array <code>[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]</code></p> <p>Your code is built for an array which looks like: <code>[[0, 0], [0, 0],[0, 0],[0, 0],[0, 0]]</code>.</p> <p>So either <code>i</code> and <code>j</code> are around the wrong way or your:</p> <pre><code>[[0 for x in range(5)] for y in range(2)] </code></pre> <p>isn't giving you what you expect.</p>
0
2016-07-29T07:57:37Z
[ "python", "arrays", "beautifulsoup" ]
python 2d array list index out of range
38,653,358
<pre><code>j=0 i=0 text=[[0 for x in range(5)]for y in range(2)] while (i&lt;5): for link in soup.findAll('td'): if j&lt;2: text[i][j]=link.string j+=1 i+=1 </code></pre> <p>The problem is I get the error message <code>list index out of range</code> but I already set the if condition so if <code>j</code> exceed <code>3</code> will nth happen. So what is the problem?</p>
-5
2016-07-29T07:52:09Z
38,653,661
<pre><code>text=[[0 for x in range(5)]for y in range(2)] </code></pre> <p>is equal to</p> <pre><code>[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] </code></pre> <p>So inside your list, you have 2 lists with 5 elements each one.</p> <p>Then look at this line:</p> <pre><code>text[i][j]=link.string </code></pre> <p><code>i</code> - is number of elements in variable <code>text</code> (you have 2)</p> <p><code>j</code> - is number of elements in each list (you have 5 elements)</p> <p>It looks like you have mixed <code>i</code> and <code>j</code>.</p>
0
2016-07-29T08:07:03Z
[ "python", "arrays", "beautifulsoup" ]
Finding same IDs in a certain amount of dictionaries in python
38,653,361
<p>I have a program that cycles through all .xml it can find in directory. It searches for device id and then adds all of them into a dictionary(i think) When I print it out it looks like </p> <pre><code>{'1.xml': [], '2.xml': []} </code></pre> <p>Next I insert the device IDs i get from the files into them so the output looks like :</p> <pre><code>{'1.xml': ['3', '12'], '2.xml': ['23', '3'']} </code></pre> <p>I'd like to get what device ids are the same so it prints out:</p> <pre><code>3 </code></pre> <p>Maybe its possible to even display from what files it got the info, but that doesn't matter too much</p>
0
2016-07-29T07:52:15Z
38,653,691
<h2>After you clarified your data</h2> <p>You can write a loop or use reduce, which you will have to import from <code>functools</code> if you are on python 3. You can use a lambda if you want, e.g. <code>lambda s1,s2: s1 &amp; s2</code> but I prefer to import the appropriate operator from the <code>operator</code> module. </p> <pre><code>In [1]: some_dict = {'1.xml': ['3', '12'], '2.xml': ['23', '3']} In [2]: from functools import reduce In [3]: from operator import and_ In [4]: reduce(and_,map(set, some_dict.values())) Out[4]: {'3'} </code></pre> <p>Equivalent for-loop would work like this:</p> <pre><code>In [8]: it = iter(some_dict.values()) In [9]: intersection = set(next(it)) In [10]: for vals in it: ...: intersection &amp;= set(vals) ...: In [11]: intersection Out[11]: {'3'} </code></pre>
0
2016-07-29T08:08:31Z
[ "python", "loops", "dictionary" ]
Finding same IDs in a certain amount of dictionaries in python
38,653,361
<p>I have a program that cycles through all .xml it can find in directory. It searches for device id and then adds all of them into a dictionary(i think) When I print it out it looks like </p> <pre><code>{'1.xml': [], '2.xml': []} </code></pre> <p>Next I insert the device IDs i get from the files into them so the output looks like :</p> <pre><code>{'1.xml': ['3', '12'], '2.xml': ['23', '3'']} </code></pre> <p>I'd like to get what device ids are the same so it prints out:</p> <pre><code>3 </code></pre> <p>Maybe its possible to even display from what files it got the info, but that doesn't matter too much</p>
0
2016-07-29T07:52:15Z
38,654,350
<p>I'm thinking of the eval function. How about putting the dictionaries into an array and generating your code dynamically.</p> <p>For example like:</p> <pre><code>list = [dict1] list.append(dict2) # append all dicts to the list for i in range(len(list)): if i == len(list) - 1: string_code += "set(dict%d)" % (i+1) else: string_code += "set(dict%d) &amp; " % (i+1) difference = eval(string_code) </code></pre> <p>Just a first idea...</p>
0
2016-07-29T08:44:46Z
[ "python", "loops", "dictionary" ]
Efficiently update columns based on one of the columns split value
38,653,421
<p>So here is my code updating many column values based on a condition of split values of the column 'location'. The code works fine, but as its iterating by row it's not efficient enough. Can anyone help me to make this code work faster please?</p> <pre><code>for index, row in df.iterrows(): print index location_split =row['location'].split(':') after_county=False after_province=False for l in location_split: if l.strip().endswith('ED'): df[index, 'electoral_district'] = l elif l.strip().startswith('County'): df[index, 'county'] = l after_county = True elif after_province ==True: if l.strip()!='Ireland': df[index, 'dublin_postal_district'] = l elif after_county==True: df[index, 'province'] = l.strip() after_province = True </code></pre>
-1
2016-07-29T07:54:56Z
38,656,102
<p>'map' was what I needed :)</p> <pre><code>def fill_county(column): res = '' location_split = column.split(':') for l in location_split: if l.strip().startswith('County'): res= l.strip() break return res df['county'] = map(fill_county, df['location']) </code></pre>
0
2016-07-29T10:08:06Z
[ "python", "dataframe" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,511
<p>When you don't specify a start or end index Python returns the entire array:</p> <pre><code>A[:] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre>
2
2016-07-29T08:00:03Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,516
<p><code>[:]</code> matches the entire list.</p> <p>So <code>A[:]</code> is the same as <code>A</code>. So <code>A[0][:]</code> is the same as <code>A[0]</code>.</p> <p>And <code>A[0][:]</code> is the same as <code>A[0]</code>.</p>
2
2016-07-29T08:00:17Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,520
<p><code>[:]</code> is equivalent to copy.</p> <p><code>A[:][0]</code> is the first row of a copy of A. <code>A[0][:]</code> is a copy of the first row of A.</p> <p>The two are the same.</p> <p>To get the first column: <code>[a[0] for a in A]</code> Or use numpy and <code>np.array(A)[:,0]</code></p>
3
2016-07-29T08:00:23Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,535
<p>Note that <code>[:]</code> just gives you a copy of <strong>all the content</strong> of the list. So what you are getting is perfectly normal. I think you wanted to use this operator as you would in <em>numpy</em> or Matlab. This does not do the same in regular Python.</p> <hr> <p><code>A[0]</code> is <code>[1, 2, 3]</code></p> <p>Therefore <code>A[0][:]</code> is also <code>[1, 2, 3]</code></p> <hr> <p><code>A[:]</code> is <code>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Therefore <code>A[:][0]</code> is <code>[1, 2, 3]</code></p> <hr> <p>If you wanted the first column you should try:</p> <pre><code>[e[0] for e in A] # [1, 4, 7] </code></pre>
2
2016-07-29T08:01:06Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,553
<p><code>A[:]</code> returns a copy of the entire list. which is <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code> <code>A[:][0]</code> Thus selects <code>[1, 2, 3]</code>. If you want the first column, do a loop:</p> <pre><code>col = [] for row in A: col.append(row[0]) </code></pre>
2
2016-07-29T08:01:55Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,555
<h3>Problem</h3> <p>A is not a 2-D list: it is a list of lists. In consideration of that:</p> <ol> <li><p><code>A[0]</code> is the first list in A:</p> <pre><code>&gt;&gt;&gt; A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; A[0] [1, 2, 3] </code></pre> <p>Consequently, <code>A[0][:]</code>: is every element of the first list:</p> <pre><code>&gt;&gt;&gt; A[0][:] [1, 2, 3] </code></pre></li> <li><p><code>A[:]</code> is every element of A, in other words it is a copy of A:</p> <pre><code>&gt;&gt;&gt; A[:] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre> <p>Consequently, <code>A[:][0]</code> is the first element of that copy of A.</p> <pre><code>&gt;&gt;&gt; A[:][0] [1, 2, 3] </code></pre></li> </ol> <h3>Solution</h3> <p>To get what you want, use numpy:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array( [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) </code></pre> <p><code>A</code> is now a true two-dimensional array. We can get the first row of <code>A</code>:</p> <pre><code>&gt;&gt;&gt; A[0,:] array([1, 2, 3]) </code></pre> <p>We can similarly get the first column of <code>A</code>:</p> <pre><code>&gt;&gt;&gt; A[:,0] array([1, 4, 7]) </code></pre> <p>`</p>
2
2016-07-29T08:02:01Z
[ "python", "list" ]
Printing a column of a 2-D List in Python
38,653,450
<p>Suppose if <code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code></p> <p>Then <code>A[0][:]</code> prints <code>[1, 2, 3]</code></p> <p>But why does <code>A[:][0]</code> print <code>[1, 2, 3]</code> again ? </p> <p>It should print the column <code>[1, 4, 7]</code>, shouldn't it?</p>
2
2016-07-29T07:56:58Z
38,653,612
<p>A is actually a list of list, not a matrix. With <code>A[:][0]</code> You are accessing the first element (the list <code>[1,2,3]</code>) of the full slice of the list A. The <code>[:]</code> is Python slice notation (explained in <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">the relevant Stack Overflow question</a>).</p> <p>To get [1,4,7] you would have to use something like <code>[sublist[0] for sublist in A]</code>, which is a <em>list comprehension</em>, a vital element of the Python language.</p>
2
2016-07-29T08:04:49Z
[ "python", "list" ]
Subfunction referencing without object declation
38,653,565
<p>I've got a class of the form:</p> <pre><code>class MyClass(object): def curves(self): def plot(self): plot a graph return something return a pd.DataFrame </code></pre> <p>What I want to do is define something I can call with <code>instance_of_my_class.curves.plot()</code></p> <p>Do I need to define curves as an object to make this possible? I'm looking for the shortest way to do it, as this is syntactic sugar only.</p> <p>Thanks.</p>
0
2016-07-29T08:02:22Z
38,653,855
<p>In order to add a level of hierarchy, <code>curves</code> needs to be an actual object, yes. There is no difference between <code>foo.curves.plot()</code> and the following:</p> <pre><code>c = foo.curves c.plot() </code></pre> <p>So <code>foo.curves</code> needs to be an object that has a <code>plot</code> method.</p> <p>Also, since the method is called on the <code>curves</code> object, the method will be bound to that object. So unless you set it up that way, the <code>curves</code> object will not have access to your actual class.</p> <p>You could pass the instance in the <code>curves</code> constructor though:</p> <pre><code>class Curves (object): def __init__ (self, parent): self.parent = parent def plot (self): self.parent._plot() class MyClass (object): def __init__ (self): self.curves = Curves(self) def _plot (self): print('Actual plot implementation') </code></pre> <p>Then you can use it as <code>foo.curves.plot()</code>:</p> <pre><code>&gt;&gt;&gt; foo = MyClass() &gt;&gt;&gt; foo.curves.plot() Actual plot implementation </code></pre> <hr> <p>You could also automate this a bit by using a <a href="http://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors">descriptor</a> for <code>curves</code>. For example, this is a possible solution:</p> <pre><code>class Accessor (object): def __init__ (self, prefix = ''): self.prefix = prefix def __get__ (self, instance, owner): return AccessorDelegate(instance, self.prefix) class AccessorDelegate (object): def __init__ (self, instance, prefix): self.instance = instance self.prefix = prefix def __getattr__ (self, name): return getattr(self.instance, self.prefix + name) </code></pre> <p>The benefit is obviously that you only need to define those a single time and then they’ll work for all your classes. You would use it like this in your class:</p> <pre><code>class MyClass (object): curves = Accessor('_curves_') def _curves_plot(self): print('Implementation of curves.plot') </code></pre> <p>Used exactly as above:</p> <pre><code>&gt;&gt;&gt; foo = MyClass() &gt;&gt;&gt; foo.curves.plot() Implementation of curves.plot </code></pre>
0
2016-07-29T08:17:59Z
[ "python" ]
python super() function error?
38,653,667
<pre><code>class car(object): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 class electricCar(car): def __init__(self, make, model, year): super().__init__(make, model, year) tesla = electricCar('tesla', 'model s', 2016) print tesla.get_descriptive_name() </code></pre> <blockquote> <p>TypeError: super() takes at least 1 argument (0 given)</p> </blockquote> <p>what is the problem with the super() function ? </p>
0
2016-07-29T08:07:18Z
38,653,762
<p><code>super()</code> (without arguments) was introduced in <strong><em>python3</em></strong> In <strong><em>python2</em></strong> you should <strong>Change it to this</strong> </p> <pre><code>class electricCar(car): def __init__(self, make, model, year): super(electricCar,self).__init__(make, model, year) </code></pre> <p>you could refer <a href="http://stackoverflow.com/questions/10482953/python-extending-with-using-super-python-3-vs-python-2">this question</a> for general inheritance syntax issue regarding <em>python2</em> and <em>python3</em></p>
2
2016-07-29T08:12:22Z
[ "python", "python-2.x" ]
python super() function error?
38,653,667
<pre><code>class car(object): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 class electricCar(car): def __init__(self, make, model, year): super().__init__(make, model, year) tesla = electricCar('tesla', 'model s', 2016) print tesla.get_descriptive_name() </code></pre> <blockquote> <p>TypeError: super() takes at least 1 argument (0 given)</p> </blockquote> <p>what is the problem with the super() function ? </p>
0
2016-07-29T08:07:18Z
38,653,779
<p>It looks like you are trying to use the Python 3 syntax, but you are using Python 2. In that version you need to pass the current class and instance as arguments to the <code>super</code> function:</p> <pre><code>super(electricCar, self).__init__(make, model, year) </code></pre>
3
2016-07-29T08:13:31Z
[ "python", "python-2.x" ]
How does Python interpret arguments in class definition?
38,653,754
<p>I am trying to understand the source code of Beautifulsoup.</p> <p>The first several lines of its source code is:</p> <pre><code>class Beautifulsoup(Tag): def __init__(self, markup="", features=None, builder=None, parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): ... </code></pre> <p>There is only one argument called "Tag" on the first line, but many more in the <strong>init</strong> function. On the other hand, I know we usually use beautifulsoup in somehow this way:</p> <pre><code>from bs4 import Beautifulsoup bsobj = Beautifulsoup(text, parser) </code></pre> <ol> <li>What is that "Tag" argument in the class definition?</li> </ol> <p>Update: As said in @BusyAnt @Vatine 's answer, Tag is not an argument but the super class of Beautifulsoup. And I found Tag's class definition in another file:</p> <pre><code>class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): "Basic constructor." </code></pre> <p>And finally PageElement is also a class defined in the same file:</p> <pre><code>class PageElement(object): """Contains the navigational information for some part of the page (either a tag or a piece of text)""" </code></pre> <p>Whooo!</p> <ol start="2"> <li>Which argument in the <strong>init</strong> correspond to text and parser in actual usage?</li> </ol>
-5
2016-07-29T08:11:53Z
38,653,866
<ol> <li><p><code>Tag</code> is the class that <code>BeautifoulSoup</code> inherits from. It's not an argument. Please <a href="http://www.python-course.eu/python3_inheritance.php" rel="nofollow">take a look at this</a> to learn more.</p></li> <li><p>As for the arguments in <code>__init__</code>: <em><code>self</code></em> refers to the instance of the class that will be created. The other arguments are written with default values, which means that they will take this value if not specified when you call the method. And as you did specify two arguments with no names in your example, the positional order will be used, that is to say <code>markers=text</code> and <code>features=parser</code>. <a href="http://www.dotnetperls.com/class-python" rel="nofollow">Here</a> would be a good way to start learning about it.</p></li> </ol> <hr> <p>I'm not willing to sound harsh, but it <em>might</em> not be the best idea to start wandering in this source code while you are not familiar with the concepts of classes, objects, and some other basic stuff in Python.</p>
1
2016-07-29T08:18:36Z
[ "python", "beautifulsoup" ]
How does Python interpret arguments in class definition?
38,653,754
<p>I am trying to understand the source code of Beautifulsoup.</p> <p>The first several lines of its source code is:</p> <pre><code>class Beautifulsoup(Tag): def __init__(self, markup="", features=None, builder=None, parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs): ... </code></pre> <p>There is only one argument called "Tag" on the first line, but many more in the <strong>init</strong> function. On the other hand, I know we usually use beautifulsoup in somehow this way:</p> <pre><code>from bs4 import Beautifulsoup bsobj = Beautifulsoup(text, parser) </code></pre> <ol> <li>What is that "Tag" argument in the class definition?</li> </ol> <p>Update: As said in @BusyAnt @Vatine 's answer, Tag is not an argument but the super class of Beautifulsoup. And I found Tag's class definition in another file:</p> <pre><code>class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): "Basic constructor." </code></pre> <p>And finally PageElement is also a class defined in the same file:</p> <pre><code>class PageElement(object): """Contains the navigational information for some part of the page (either a tag or a piece of text)""" </code></pre> <p>Whooo!</p> <ol start="2"> <li>Which argument in the <strong>init</strong> correspond to text and parser in actual usage?</li> </ol>
-5
2016-07-29T08:11:53Z
38,654,005
<p>The line <code>class BeautifulSoup(Tag):</code> means "please start defining a class named BeautifulSoup, inheriting from the class Tag".</p> <p>The line(s) <code>def __init__(self, markup="", features=None...</code> mean "let the class's constructor take the arguments ...", with the very first one being the instance the constructor method is invoked on (it's not necessary to call this <code>self</code>, but it is <strong>strongly</strong> recommended). The rest of the arguments work like that of a normal function.</p> <p>In the specific invocation you've shown, <code>markup</code> will get the value of <code>text</code> and <code>features</code> that of <code>parser</code> (you're not using any keywords, so they'll be positional, with most of them having default values).</p>
1
2016-07-29T08:25:09Z
[ "python", "beautifulsoup" ]
Python Error - For and IF NOT in same statement
38,653,839
<p>I'm using Python 3.5, i am trying to remove NLTK stopWords from my dataset and when i run the a statement which combines both For &amp; IF NOT in one statement i get an error. Searching for the error did not yield any useful results.</p> <p>Code and error snapshot attached below enter image description here</p> <pre><code>base_data['stemmed_stop_comments'] = [word for word in base_data['stemmed_comments'] if not word in stopWords] </code></pre> <blockquote> <p>ValueError: Length of values does not match length of index</p> </blockquote>
0
2016-07-29T08:16:55Z
38,653,933
<p>It seems you don't have key in base_data as 'stemmed_comments'. Use statement like this</p> <pre><code>base_data['stemmed_stop_comments'] = [] if 'stemmed_comments' in base_data: base_data['stemmed_stop_comments'] = [word for word in base_data['stemmed_comments'] if not (word in stopWords)] </code></pre> <p>or</p> <pre><code>if 'stemmed_comments' in base_data: base_data['stemmed_stop_comments'] = [word for word in base_data['stemmed_comments'] if word not in stopWords] </code></pre> <p>or</p> <pre><code>if 'stemmed_comments' in base_data: base_data['stemmed_stop_comments'] = filter(lambda word: word not in stopWords, base_data['stemmed_comments']) </code></pre>
-2
2016-07-29T08:21:34Z
[ "python", "nltk", "stop-words" ]
Python Error - For and IF NOT in same statement
38,653,839
<p>I'm using Python 3.5, i am trying to remove NLTK stopWords from my dataset and when i run the a statement which combines both For &amp; IF NOT in one statement i get an error. Searching for the error did not yield any useful results.</p> <p>Code and error snapshot attached below enter image description here</p> <pre><code>base_data['stemmed_stop_comments'] = [word for word in base_data['stemmed_comments'] if not word in stopWords] </code></pre> <blockquote> <p>ValueError: Length of values does not match length of index</p> </blockquote>
0
2016-07-29T08:16:55Z
38,659,835
<pre><code>def remove_stop(sentance): removed = [x for x in sentance.split(' ') if x.lower() not in stopWords] return ' '.join(removed) base_data['stemmed_stop_comments'] = base_data.stemmed_comments.apply(lambda x: remove_stop(x)) </code></pre>
0
2016-07-29T13:12:46Z
[ "python", "nltk", "stop-words" ]
Python load JSON only loads part of a file
38,653,925
<p>This is a simple code example:</p> <pre><code>import json f = open("somefile.json") d = json.load(f) print d # output: f.seek(0) l = f.readlines() print l </code></pre> <p><strong>output</strong></p> <pre><code>{u'95659045': {u'90': False}} ['{"95659045": {"1": false}, "95659045": {"90": false}}'] </code></pre> <p>The <a href="https://docs.python.org/2.7/library/json.html?highlight=json%20load#json.load" rel="nofollow">documentation</a> suggests, that the whole file should be loaded.</p> <p>I honestly have no idea</p>
0
2016-07-29T08:21:15Z
38,653,988
<p>You have the same key twice '95659045', so the second occurrence overwrite the first.</p>
2
2016-07-29T08:24:19Z
[ "python", "json" ]
Matrix - String, Int, and Combined Operations
38,654,086
<p>I want to be able to assign a string (a word) to an integer, and also an integer to a string, so that later on when i sort the integer or string, i can print the corresponding string or integer to that unit in matrix. Example;</p> <pre><code>103 = QWE 13 = ASD 50 = ZXC -1 = VBN 253 = RTY </code></pre> <p>and even multiple positions, like;</p> <pre><code>105 = QWE 103 = QWE </code></pre> <p>then,</p> <pre><code>matrix = [105,103,13,50,-1,253] sort = [-1,13,50,103,105,253] print sort_strings # output: VBN ASD ZXC QWE QWE RTY </code></pre> <p>Just like in .cvs, when a column sorted other columns move according to keep row intact. And would like to do some additional functions on file, like classifying those strings after output so I can make some charts with color for visualization.</p> <p>Thanks</p>
0
2016-07-29T08:29:54Z
38,662,920
<p>It can be done by MATLAB. I tried to do it using vectorization method. And it became the more and more unclear at each step but I spent a lot of time for it, so I show it:</p> <pre><code>a1 = ['qve';'rts';'abc';'abc';'def'] a2 = [3;5;10;7;8] %//find unique strings: mycell = unique(a1,'rows') %//find numbers corresponded to each string. %//You can see there are 2 numbers correspond to string 'abc' indexes = arrayfun(@(x) find(all(ismember(a1,mycell(x,:)),2)), 1:size(mycell,1), 'UniformOutput',0) %//create some descriptive cell array: mycell2 = arrayfun( @(x) a2(indexes{x}), 1:size(mycell,1),'UniformOutput',0) mycell = cellstr(mycell) mycell = [mycell mycell2'] %' %------------------------------------------------------------------------- %// now create test array (I use sort like you) a3 = sort(cell2mat(mycell(:,2))) %//last step: find each index of a3 in every cell of mycell and put corresponding string to res res = mycell(arrayfun( @(y) find ( cellfun( @(x) any(ismember(x,y)), mycell(:,2))), a3),1) </code></pre> <p><code>a1</code> and <code>a2</code> is input data. It creates manually. And <code>res</code> is a result you need:</p> <pre><code>res = 'qve' 'rts' 'abc' 'def' 'abc' </code></pre> <p>P.S. It works! But it looks like some brainblow so I suggest to use loops.</p>
0
2016-07-29T15:53:40Z
[ "python", "matlab" ]
Matrix - String, Int, and Combined Operations
38,654,086
<p>I want to be able to assign a string (a word) to an integer, and also an integer to a string, so that later on when i sort the integer or string, i can print the corresponding string or integer to that unit in matrix. Example;</p> <pre><code>103 = QWE 13 = ASD 50 = ZXC -1 = VBN 253 = RTY </code></pre> <p>and even multiple positions, like;</p> <pre><code>105 = QWE 103 = QWE </code></pre> <p>then,</p> <pre><code>matrix = [105,103,13,50,-1,253] sort = [-1,13,50,103,105,253] print sort_strings # output: VBN ASD ZXC QWE QWE RTY </code></pre> <p>Just like in .cvs, when a column sorted other columns move according to keep row intact. And would like to do some additional functions on file, like classifying those strings after output so I can make some charts with color for visualization.</p> <p>Thanks</p>
0
2016-07-29T08:29:54Z
38,767,663
<p>What you're doing is called "sorting arrays in parallel" or "sorting parallel arrays." You can use those terms to search for guides on how to do it. However, below is some code which shows one way to do it in MATLAB:</p> <pre><code>unsorted_keys = [95, 37, 56, 70, 6, 61, 58, 13, 57, 7, 68, 52, 98, 25, 12]; unsorted_strings = cell(size(unsorted_keys)); unsorted_strings = {'crumply', 'going', 'coyotes', 'aficionado', 'bob', 'timeless', 'last', 'bloke', 'brilliant', 'reptile', 'reptile', 'reptile', 'reptile', 'reptile', 'reptile'}; [sorted_keys, indicies] = sort(unsorted_keys); % indicies = [5, 10, 15, 8, 14, 2, 12, 3, 9, 7 6, 11, 4, 1, 13] % So, the 5th element of unsorted_keys became the 1st element of sorted_keys % the 10th element of unsorted_keys became the 2nd element of sorted_keys % the 15th element of unsorted_keys became the 3rd element of sorted_keys % the 8th element of unsorted_keys became the 4th element of sorted_keys % and so on..... % sorted_keys == unsorted_keys(indicies) sorted_strings = unsorted_strings(indicies); </code></pre>
0
2016-08-04T12:42:39Z
[ "python", "matlab" ]
How to find line break in text file using Pyspark?
38,654,092
<p>I am trying to load text file in spark, I am getting error like </p> <pre><code>Input row doesn't have expected number of values required by the schema. 31 fields are required while 1 values are provided. </code></pre> <p>the file size is 20GB. Manually its not possible to check line by line. What is the best option to find the line break and to load the file? I am using pyspark to load.</p>
0
2016-07-29T08:30:09Z
38,662,631
<p>You can do a fast check with pySpark.</p> <p>Try to load your file like this:</p> <pre><code>rdd = sc.textFile('filePath').map(lambda x: x.split('&lt;yourSeparator&gt;')) rdd.map(lambda x: len(x)).zipWithIndex().sortByKey().take(5) </code></pre> <p>this will return the index of the Column lenght and the index of it (started with 0)</p>
0
2016-07-29T15:38:16Z
[ "python", "apache-spark", "pyspark" ]
Python/Pyomo with glpk Solver - Error
38,654,200
<p>I am trying to run some simle example with Pyomo + glpk Solver (Anaconda2 64bit Spyder):</p> <pre><code>from pyomo.environ import * model = ConcreteModel() model.x_1 = Var(within=NonNegativeReals) model.x_2 = Var(within=NonNegativeReals) model.obj = Objective(expr=model.x_1 + 2*model.x_2) model.con1 = Constraint(expr=3*model.x_1 + 4*model.x_2 &gt;= 1) model.con2 = Constraint(expr=2*model.x_1 + 5*model.x_2 &gt;= 2) opt = SolverFactory("glpk") instance = model.create() #results = opt.solve(instance) #results.write() </code></pre> <p>But i get the following error message:</p> <pre><code>invalid literal for int() with base 10: 'c' Traceback (most recent call last): File "&lt;ipython-input-5-e074641da66d&gt;", line 1, in &lt;module&gt; runfile('D:/..../Exampe.py', wdir='D:.../exercises/pyomo') File "C:\...\Continuum\Anaconda21\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "C:\....\Continuum\Anaconda21\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "D:/...pyomo/Exampe.py", line 34, in &lt;module&gt; results = opt.solve(instance) File "C:\....\Continuum\Anaconda21\lib\site-packages\pyomo\opt\base\solvers.py", line 580, in solve result = self._postsolve() File "C:\...Continuum\Anaconda21\lib\site-packages\pyomo\opt\solver\shellcmd.py", line 267, in _postsolve results = self.process_output(self._rc) File "C:\...\Continuum\Anaconda21\lib\site-packages\pyomo\opt\solver\shellcmd.py", line 329, in process_output self.process_soln_file(results) File "C:\....\Continuum\Anaconda21\lib\site-packages\pyomo\solvers\plugins\solvers\GLPK.py", line 454, in process_soln_file raise ValueError(msg) ValueError: Error parsing solution data file, line 1 </code></pre> <p>I downloaded glpk from <a href="http://winglpk.sourceforge.net/" rel="nofollow">http://winglpk.sourceforge.net/</a> --> unziped + added parth to the environmental variable "path".</p> <p>Hope someone can help me - thank you!</p>
2
2016-07-29T08:35:51Z
39,111,341
<p>This is a known problem with GLPK 4.60 (glpsol changed the format of their output which broke Pyomo 4.3's parser). You can either download an older release of GLPK, or upgrade Pyomo to 4.4.1 (which contains an updated parser).</p>
1
2016-08-23T21:59:34Z
[ "python", "pyomo" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,527
<p>Use <a href="https://docs.python.org/3/library/glob.html?highlight=glob#glob.glob" rel="nofollow">glob.glob</a></p> <pre><code>import glob print( glob.glob('AM_INMAG_Export_????-??-??.csv')[-1] ) </code></pre> <p>This will work if the time defined in the name is actually the updated time. Otherwise , you should use <a href="https://docs.python.org/3/library/os.html?highlight=os#os.stat" rel="nofollow">os.stat</a> to find </p> <pre><code>import glob import os def find_last_updated(pattern): def find_updated(ff): return os.stat(ff).st_mtime last = None last_updated = 0 for ff in glob.glob(pattern): ff_updated = find_updated(ff) if last == None or ff_updated &gt; last_updated : last = ff last_updated = ff_updated return last print(find_last_updated('AM_INMAG_Export-????-??-??.csv')) </code></pre>
0
2016-07-29T08:53:29Z
[ "python" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,528
<p>So it looks like you need to use regex to get the date as a group item. Once you have all of the groups you need to convert that to a python date and then check to see which one has the greatest date.</p> <pre><code>import re pat = re.compile("^AM_INMAG_Export_(.+)\.csv$") matches = pat.match(your_data) </code></pre> <p>This is the regular expression you will be looking to use, you could go into more detail around the grouping and get an actual date format you are looking for.</p>
0
2016-07-29T08:53:31Z
[ "python" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,532
<p>Filter the files that match your desired prefix and then sort.</p> <pre><code>&gt;&gt;&gt; files = """ERROR_AM_INMAG_Export_2016-07-25.csv ... AM_INMAG_Export_2016-07-26_done.csv ... ERROR_AM_INMAG_Export_2016-07-27.csv ... AM_INMAG_Export_2016-07-28_done.csv ... AM_INMAG_Export_2016-07-29.csv ... file1 ... file2 ... fileN""".split('\n') &gt;&gt;&gt; files ['ERROR_AM_INMAG_Export_2016-07-25.csv', 'AM_INMAG_Export_2016-07-26_done.csv ', 'ERROR_AM_INMAG_Export_2016-07-27.csv', 'AM_INMAG_Export_2016-07-28_done.csv ', 'AM_INMAG_Export_2016-07-29.csv', 'file1', 'file2', 'fileN'] &gt;&gt;&gt; filtered_files = [ x for x in files if x.startswith('AM_INMAG_Export_')] &gt;&gt;&gt; sorted_files = sorted(filtered_files,reverse=True) &gt;&gt;&gt; sorted_files[0] 'AM_INMAG_Export_2016-07-29.csv' </code></pre> <hr> <p><strong>Update</strong></p> <p>Filter filenames with a regexp and then sort.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; files = [ ... 'ERROR_AM_INMAG_Export_2016-07-25.csv', ... 'AM_INMAG_Export_2016-07-26_done.csv', ... 'ERROR_AM_INMAG_Export_2016-07-27.csv', ... 'AM_INMAG_Export_2016-07-28_done.csv', ... 'AM_INMAG_Export_2016-07-21.csv', ... 'AM_INMAG_Export_2016-07-25.csv', ... 'AM_INMAG_Export_2016-07-29.csv', ... 'file1', ... 'file2', ... 'fileN' ... ] &gt;&gt;&gt; &gt;&gt;&gt; file_re = re.compile(r'^AM_INMAG_Export_\d{4}-\d{2}-\d{2}.csv$') &gt;&gt;&gt; filtered_files = [ x for x in files if file_re.match(x)] &gt;&gt;&gt; sorted_files = sorted(filtered_files,reverse=True) &gt;&gt;&gt; sorted_files[0] 'AM_INMAG_Export_2016-07-29.csv' </code></pre>
0
2016-07-29T08:53:38Z
[ "python" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,547
<pre><code>files = glob.glob('AM_INMAG_Export_*.csv') sorted_files = sorted(files, key=lambda x: int(x.split('_')[3].split('.')[0])) </code></pre>
1
2016-07-29T08:54:04Z
[ "python" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,636
<p>use <code>glob</code> to get the files and then sort the file names from the earliest to the oldest file:</p> <pre><code>files = glob.glob('&lt;YOUR_DIRECTORY&gt;/AM_INMAG_Export_*') # the file prefix + '*' as regex files.sort(reverse=True) # sort and use 'reverse=True' to get a list of files sorted by the earliest to the oldest your_precious_file = files[0] # the one with the oldest date </code></pre> <p><strong>Note:</strong> the assumption here is that all files have identical prefix and post-fix, and the difference is due to the date.</p>
0
2016-07-29T08:58:33Z
[ "python" ]
Python Regular expression to find latest file in directory
38,654,202
<p>I have one directory which contains below files for example purpose.</p> <pre><code>Directory: ERROR_AM_INMAG_Export_2016-07-25.csv AM_INMAG_Export_2016-07-26_done.csv ERROR_AM_INMAG_Export_2016-07-27.csv AM_INMAG_Export_2016-07-28_done.csv AM_INMAG_Export_2016-07-29.csv file1 file2 fileN </code></pre> <p>Here how can i retrieve file which starts with ""AM_INMAG_Export_" and it should have latest timestamp using <strong>Python</strong>. for example: "AM_INMAG_Export_2016-07-29.csv" is the file I want to retrieve. <strong>BUT "fileN" is the latest modified file in the directory.</strong></p>
0
2016-07-29T08:35:56Z
38,654,830
<p>A list of files obtained with glob.glob() can be sorted with the sorted statement. See the following example</p> <pre><code>import os import glob def main(): """ Sort csv Files. """ for f in sorted(glob.glob(os.path.join('AM_INMAG_Export_*.csv')), reverse=True): print("File " + f) if __name__ == "__main__": main() </code></pre>
0
2016-07-29T09:07:48Z
[ "python" ]
what does this statement (line, str) = str.split("\n", 1) mean?
38,654,238
<p>I am familiar with the <code>split</code> function and I would use it as such: </p> <pre><code>str = "Line1-abcdef \nLine2-abc \nLine4-abcd" print str.split( ) </code></pre> <p>The above would return this:</p> <pre><code>['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] </code></pre> <p>Simple and easy. However, I came across a piece of code that has this statement: </p> <pre><code>(line, str) = str.split("\n", 1) </code></pre> <p>There are two things that I dont understand here:</p> <ol> <li><p>The second parameter of <code>split</code> and what that does. I looked <a href="http://www.tutorialspoint.com/python/string_split.htm" rel="nofollow">here</a> and it says the number of lines made. What does that mean?</p></li> <li><p><code>split</code> returns an iterable vector. Why is it being assigned to <code>(line, str)</code>? What does <code>(line, str)</code> mean here?</p></li> </ol>
-2
2016-07-29T08:38:27Z
38,654,278
<p>The second argument <code>maxsplit=1</code> means <em>stop splitting after you meet the separator <code>\n</code> once</em>.</p> <p>Therefore you have only two parts, your line and the rest of the string. You should really take a look at examples, starting <a class='doc-link' href="http://stackoverflow.com/documentation/python/278/string-methods/1007/split-a-string-based-on-a-delimiter-into-a-list-of-strings#t=201607290844236959563">here</a></p> <hr> <p>For example:</p> <pre><code>str = 'This is one line\nThis is a second line\nThis is a third line' (line, str) = str.split('\n', 1) print(line) # 'This is one line' print(str) # 'This is a second line\nThis is a third line' </code></pre>
5
2016-07-29T08:41:06Z
[ "python", "string", "iterable" ]
what does this statement (line, str) = str.split("\n", 1) mean?
38,654,238
<p>I am familiar with the <code>split</code> function and I would use it as such: </p> <pre><code>str = "Line1-abcdef \nLine2-abc \nLine4-abcd" print str.split( ) </code></pre> <p>The above would return this:</p> <pre><code>['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] </code></pre> <p>Simple and easy. However, I came across a piece of code that has this statement: </p> <pre><code>(line, str) = str.split("\n", 1) </code></pre> <p>There are two things that I dont understand here:</p> <ol> <li><p>The second parameter of <code>split</code> and what that does. I looked <a href="http://www.tutorialspoint.com/python/string_split.htm" rel="nofollow">here</a> and it says the number of lines made. What does that mean?</p></li> <li><p><code>split</code> returns an iterable vector. Why is it being assigned to <code>(line, str)</code>? What does <code>(line, str)</code> mean here?</p></li> </ol>
-2
2016-07-29T08:38:27Z
38,654,298
<p>Testing with a basic string, <code>how do you do ?</code>. <code>line</code> will get the first element of the split, and <code>str</code> will get the rest (as we only split once)</p>
0
2016-07-29T08:42:10Z
[ "python", "string", "iterable" ]
Django. Cannot load picture from ImageField
38,654,297
<p>I'm trying to upload a picture from ImageField in template, but it is not displayed. Code and screenshots will explain better.</p> <p>settings.py</p> <pre><code>STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = '/media/veracrypt1/django/pycaba/pycaba/media/' </code></pre> <p>models.py</p> <pre><code>image = models.ImageField() </code></pre> <p>views.py</p> <pre><code>def thread(request, boardname, thread_id): board = boardname thread = thread_id op_post = get_object_or_404(Posts, board=board, id=thread_id) return render(request, 'board/thread.html', {'op_post':op_post}) </code></pre> <p>thread.html</p> <pre><code>{% extends 'board/base.html' %} {% block content %} &lt;div class="op_post"&gt; &lt;img src="{{op_post.image.url}}"&gt; &lt;/div&gt; {% endblock content %} </code></pre> <p>thread.html source in browser</p> <p><a href="http://i.stack.imgur.com/J1v7i.jpg" rel="nofollow">enter image description here</a></p>
0
2016-07-29T08:42:00Z
38,654,440
<p>What Django version are you using? Have you included <a href="https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">static file urls</a> in you url patterns?</p>
0
2016-07-29T08:48:57Z
[ "python", "django" ]
How can I sort contours from left to right and top to bottom?
38,654,302
<p>I am trying to build an character recognition program using Python. I am stuck on sorting the contours. I am using <a href="https://github.com/guard0g/HandwritingRecognition/blob/master/Handwriting%20Recognition%20Workbook.ipynb" rel="nofollow">this page</a> as a reference. </p> <p>I managed to find the contours using the following piece of code:</p> <pre><code>mo_image = di_image.copy() contour0 = cv2.findContours(mo_image.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) contours = [cv2.approxPolyDP(cnt,3,True) for cnt in contour0[0]] </code></pre> <p>And added the bounding rectangles and segmented the image using this part of the code: </p> <pre><code>maxArea = 0 rect=[] for ctr in contours: maxArea = max(maxArea,cv2.contourArea(ctr)) if img == "Food.jpg": areaRatio = 0.05 elif img == "Plate.jpg": areaRatio = 0.5 for ctr in contours: if cv2.contourArea(ctr) &gt; maxArea * areaRatio: rect.append(cv2.boundingRect(cv2.approxPolyDP(ctr,1,True))) symbols=[] for i in rect: x = i[0] y = i[1] w = i[2] h = i[3] p1 = (x,y) p2 = (x+w,y+h) cv2.rectangle(mo_image,p1,p2,255,2) image = cv2.resize(mo_image[y:y+h,x:x+w],(32,32)) symbols.append(image.reshape(1024,).astype("uint8")) testset_data = np.array(symbols) cv2.imshow("segmented",mo_image) plt.subplot(2,3,6) plt.title("Segmented") plt.imshow(mo_image,'gray') plt.xticks([]),plt.yticks([]); </code></pre> <p>However the resulting segments appear in to be in random order. Here is the original image followed by the processed image with detected segments.</p> <p><a href="http://i.stack.imgur.com/TCZ1H.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/TCZ1H.jpg" alt="segments"></a></p> <p>The program then outputs each segment separately, however it is in the order: <code>4 1 9 8 7 5 3 2 0 6</code> and not <code>0 1 2 3 4 5 6 7 8 9</code>. Simply adding a sort operation in "rect" fixes this, but the same solution wont work for a document with multiple lines.</p> <p>So my question is: How do I sort the contours from left to right and top to bottom?</p>
1
2016-07-29T08:42:17Z
38,693,156
<p>I don't think you are going to be able to generate the contours directly in the correct order, but a simple sort as follows should do what you need:</p> <pre><code>import numpy as np c = np.load(r"rect.npy") contours = list(c) # Example - contours = [(287, 117, 13, 46), (102, 117, 34, 47), (513, 116, 36, 49), (454, 116, 32, 49), (395, 116, 28, 48), (334, 116, 31, 49), (168, 116, 26, 49), (43, 116, 30, 48), (224, 115, 33, 50), (211, 33, 34, 47), ( 45, 33, 13, 46), (514, 32, 32, 49), (455, 32, 31, 49), (396, 32, 29, 48), (275, 32, 28, 48), (156, 32, 26, 49), (91, 32, 30, 48), (333, 31, 33, 50)] max_width = np.sum(c[::, (0, 2)], axis=1).max() max_height = np.max(c[::, 3]) nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) for x, y, w, h in contours: print "{:4} {:4} {:4} {:4}".format(x, y, w, h) </code></pre> <p>This would display the following output:</p> <pre><code> 36 45 33 40 76 44 29 43 109 43 29 45 145 44 32 43 184 44 21 43 215 44 21 41 241 43 34 45 284 46 31 39 324 46 7 39 337 46 14 41 360 46 26 39 393 46 20 41 421 45 45 41 475 45 32 41 514 43 38 45 39 122 26 41 70 121 40 48 115 123 27 40 148 121 25 45 176 122 28 41 212 124 30 41 247 124 91 40 342 124 28 39 375 124 27 39 405 122 27 43 37 210 25 33 69 199 28 44 102 210 21 33 129 199 28 44 163 210 26 33 195 197 16 44 214 210 27 44 247 199 25 42 281 212 7 29 292 212 11 42 310 199 23 43 340 199 7 42 355 211 43 30 406 213 24 28 437 209 31 35 473 210 28 43 506 210 28 43 541 210 17 31 37 288 21 33 62 282 15 39 86 290 24 28 116 290 72 30 192 290 23 30 218 290 26 41 249 288 20 33 </code></pre> <p>It works by grouping similar <code>y</code> values and then multiplying by the width, the result is a key that increases row by row. The maximum height of a single rectangle is calculated to determine a suitable grouping value for <code>nearest</code>. The <code>1.4</code> value is a line spacing value. This could also be calculated automatically. So for both of your examples <code>nearest</code> is about 70.</p> <p>The calculations could also be done directly in numpy.</p>
0
2016-08-01T07:27:03Z
[ "python" ]
Python thread safety for method/attribute lookup
38,654,375
<p>I have been working with python and I understand and use the threading, queues, events, locks in a multi threaded environment. What I am curious about is while accesing and calling a shared object's method can we ignore any locks and semaphores? Here is a sample code:</p> <pre><code>import threading class Methods(object): def method1(self): # assume there is no need for a lock # only local variables are used pass def method2(self): # assume there is no need for a lock # only local variables are used pass methods = Methods() def thread1(): # instance method is found from instance dictionary # and called methods.method1() def thread2(): # instance method is found from instance dictionary # and called methods.method2() thr1 = threading.Thread(None, thread1) thr2 = threading.Thread(None, thread2) thr1.start() # assume thr1 and thr2 is started at the same time thr2.start() thr1.join() thr2.join() </code></pre> <p>Thread 1 and Thread 2 calls the same <code>methods</code> <code>method1</code> and <code>method2</code> at the same time (just assume). <code>methods.method1</code> and <code>methods.method2</code> cause a dictionary lookup using <code>self.__dict__</code> or <code>__getattribute__</code> method, right? So, do we need any locks in this simple scenario? I wonder if internal dictionary lookup of an instance is atomic and what happens if <code>self.__dict__</code> is updated somehow during execution. I have not found such resource on the internet. I appreciate if you could help me to clarify these thoughts.</p>
0
2016-07-29T08:45:52Z
38,654,802
<p>I think if you use only local variables then its ok, but if you only use local variables in your methods (I mean you don't access attributes of <code>self</code>), maybe it's better to make them staticmethods or plain functions?</p>
0
2016-07-29T09:06:05Z
[ "python", "multithreading", "cpython" ]
Python pip installation in ubuntu
38,654,445
<p>I am new to Ubuntu and was trying to install pip using get-pip.py , when I received this message.</p> <pre><code>Requirement already up-to-date: pip in /usr/local/lib/python2.7/dist- packages/pip-8.1.2-py2.7.egg </code></pre> <p>But when I enter <code>pip -V</code>, I receive an error saying :</p> <pre><code>The 'pip==7.1.0' distribution was not found and is required by the application </code></pre> <p><a href="http://imgur.com/a/Sh7l5" rel="nofollow">Complete error</a></p> <p>I was trying to install new packages using <code>pip install &lt;packagename&gt;</code> but this command gives the same error as previous . </p>
1
2016-07-29T08:49:08Z
38,654,603
<p>I suggest installing pip using the package manager. Open up a terminal and enter</p> <pre><code>sudo apt-get install python-pip </code></pre> <p>That <em>should</em> install the <a href="http://packages.ubuntu.com/xenial/python-pip" rel="nofollow">pip</a> ubunutu package.</p>
2
2016-07-29T08:56:42Z
[ "python", "ubuntu", "pip" ]
Python pip installation in ubuntu
38,654,445
<p>I am new to Ubuntu and was trying to install pip using get-pip.py , when I received this message.</p> <pre><code>Requirement already up-to-date: pip in /usr/local/lib/python2.7/dist- packages/pip-8.1.2-py2.7.egg </code></pre> <p>But when I enter <code>pip -V</code>, I receive an error saying :</p> <pre><code>The 'pip==7.1.0' distribution was not found and is required by the application </code></pre> <p><a href="http://imgur.com/a/Sh7l5" rel="nofollow">Complete error</a></p> <p>I was trying to install new packages using <code>pip install &lt;packagename&gt;</code> but this command gives the same error as previous . </p>
1
2016-07-29T08:49:08Z
38,654,711
<p>You should not be installing pip for the default python installation, neither from the package manager nor using <code>get-pip.py</code>. So you can never use it to break the system python. </p> <p>Instead always use <code>virtualenv</code> (created from the default/system python or from a newer version), activate and use <code>pip</code> in that environment.</p>
2
2016-07-29T09:02:00Z
[ "python", "ubuntu", "pip" ]
Python 3, ImportError: cannot import name 'HTTPClient'
38,654,492
<p>I'm fairly new to python am interested in making a script for discord. After installing everything I was supposed to and plugging in the example code, I am getting errors.</p> <pre><code>import discord import asyncio client = discord.Client() async def my_background_task(): await client.wait_until_ready() counter = 0 channel = discord.Object(id='channel_id_here') while not client.is_closed: counter += 1 await client.send_message(channel, counter) await asyncio.sleep(60) # task runs every 60 seconds @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.loop.create_task(my_background_task()) client.run('token') </code></pre> <p>Error:</p> <pre><code>F:\Python\python.exe "F:/Python Projects/DiscordPlugin1.py" Traceback (most recent call last): File "F:/Python Projects/DiscordPlugin1.py", line 1, in &lt;module&gt; import discord File "F:\Python\lib\site-packages\discord\__init__.py", line 20, in &lt;module&gt; from .client import Client, AppInfo, ChannelPermissions File "F:\Python\lib\site-packages\discord\client.py", line 45, in &lt;module&gt; from .http import HTTPClient ImportError: cannot import name 'HTTPClient' Process finished with exit code 1 </code></pre> <p>If anyone could at least point me in the right direction that would be much appreciated.</p>
2
2016-07-29T08:51:19Z
38,654,706
<p>It seems that file <code>discord/http.py</code> does not contain definition of <code>HTTPClient</code>. Can you please provide contents of this file?</p>
0
2016-07-29T09:01:34Z
[ "python", "python-3.x", "httpclient" ]
Python 3, ImportError: cannot import name 'HTTPClient'
38,654,492
<p>I'm fairly new to python am interested in making a script for discord. After installing everything I was supposed to and plugging in the example code, I am getting errors.</p> <pre><code>import discord import asyncio client = discord.Client() async def my_background_task(): await client.wait_until_ready() counter = 0 channel = discord.Object(id='channel_id_here') while not client.is_closed: counter += 1 await client.send_message(channel, counter) await asyncio.sleep(60) # task runs every 60 seconds @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.loop.create_task(my_background_task()) client.run('token') </code></pre> <p>Error:</p> <pre><code>F:\Python\python.exe "F:/Python Projects/DiscordPlugin1.py" Traceback (most recent call last): File "F:/Python Projects/DiscordPlugin1.py", line 1, in &lt;module&gt; import discord File "F:\Python\lib\site-packages\discord\__init__.py", line 20, in &lt;module&gt; from .client import Client, AppInfo, ChannelPermissions File "F:\Python\lib\site-packages\discord\client.py", line 45, in &lt;module&gt; from .http import HTTPClient ImportError: cannot import name 'HTTPClient' Process finished with exit code 1 </code></pre> <p>If anyone could at least point me in the right direction that would be much appreciated.</p>
2
2016-07-29T08:51:19Z
38,671,132
<p>Installing a different version of discord.py seemed to work.</p> <p>pip install -U <a href="https://github.com/Rapptz/discord.py/archive/master.zip#egg=discord.py[voice]" rel="nofollow">https://github.com/Rapptz/discord.py/archive/master.zip#egg=discord.py[voice]</a></p> <p>This was the version I used.</p>
0
2016-07-30T06:42:09Z
[ "python", "python-3.x", "httpclient" ]
Softmax matrix to 0/1 (OneHot) encoded matrix?
38,654,543
<p>Suppose I have the following tensor <code>t</code> as the output of a softmax function:</p> <pre><code>t = tf.constant(value=[[0.2,0.8], [0.6, 0.4]]) &gt;&gt; [ 0.2, 0.8] [ 0.6, 0.4] </code></pre> <p>Now I would like to convert this matrix <code>t</code> into a matrix that resembles the OneHot encoded matrix:</p> <pre><code>Y.eval() &gt;&gt; [ 0, 1] [ 1, 0] </code></pre> <p>I am familiar with <code>c = tf.argmax(t)</code> that would give me the indices per row of <code>t</code> that should be 1. But to go from <code>c</code> to <code>Y</code> seems quite difficult. </p> <p>What I already tried was converting <code>t</code> to <code>tf.SparseTensor</code> using <code>c</code> and then using <code>tf.sparse_tensor_to_dense()</code> to get <code>Y</code>. But that conversion involves quite some steps and seems overkill for the task - I haven't even finished it completely but I am sure it can work. </p> <p>Is there any more appropriate/easy way to make this conversion that I am missing.</p> <p><em>The reason why I need this is because I have a custom OneHot encoder in Python where I can feed <code>Y</code>. <a href="https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#one_hot" rel="nofollow"><code>tf.one_hot()</code></a> is not extensive enough - doesn't allow custom encoding.</em></p> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/34685947/adjust-single-value-within-tensor-tensorflow">Adjust Single Value within Tensor -- TensorFlow</a></li> </ul>
1
2016-07-29T08:53:54Z
38,655,309
<p>Why not combine tf.argmax() with tf.one_hot().</p> <p><code>Y = tf.one_hot(tf.argmax(t, dimension = 1), depth = 2)</code></p>
1
2016-07-29T09:31:29Z
[ "python", "tensorflow" ]
How to use regexp has whitespace in brackets by using Python3
38,654,588
<p>My code is like this:</p> <pre><code>import re s = """ &lt;contentID&gt;1""" reg = re.compile("(.|\n)+&lt;contentID&gt;1.*") m = reg.fullmatch(s) print(m) reg = re.compile("[.\n]+&lt;contentID&gt;1.*") m = reg.fullmatch(s) print(m) </code></pre> <p>Seems like the regex <code>[.\n]</code> does not work, but <code>(.|\n)</code> does. Why? And how to write a RegExp when using brackets in this situation?</p>
1
2016-07-29T08:55:59Z
38,654,744
<p>Instead of the <code>[.\n]</code> that matches a newline or a literal dot character, use <code>.</code> with <code>re.DOTALL</code> or <code>re.S</code> enabling the <code>.</code> to match newline symbols, too:</p> <pre><code>reg = re.compile(".*&lt;contentID&gt;1.*", re.DOTALL) m = reg.fullmatch(s) print(m) </code></pre> <p>See the <a href="https://ideone.com/ruC787" rel="nofollow">Python demo</a></p> <p>Also, see <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">Python <code>re</code> reference</a>:</p> <blockquote> <p><strong><code>[]</code></strong><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Used to indicate a set of characters. In a set:<br/> ...<br/> <li> Special characters lose their special meaning inside sets. For example, <code>[(+*)]</code> will match any of the literal characters <code>(</code>, <code>+</code>, <code>*</code>, or <code>)</code>.</p> </blockquote> <p>If you do not use <code>fullmatch</code> but <code>search</code>, you can just use <code>reg = re.compile("&lt;contentID&gt;1")</code> or <code>if "&lt;contentID&gt;1" in s</code>.</p>
1
2016-07-29T09:03:48Z
[ "python", "regex", "whitespace", "brackets" ]
Flask SQLAlchemy many-to-many relationship new attribute
38,654,624
<p>I am using Flask and SQLAlchemy and many to many relationship in my database. It works fine but I would like to add new attributes(String tarif) in my table <code>user_routes</code>. How can I edit this attribute in query? It is possible? Thank you</p> <p>This is my db query to insert </p> <pre><code>route = get_route(request.form['fromStation'],request.form['toStation'],date_object) user = get_user(request.form['userToken']) route.users.append(user) user.routes.append(route) db.session.commit() </code></pre> <h1>Models</h1> <pre><code>from app import db user_routes = db.Table('user_routes', db.Column('route_id', db.Integer, db.ForeignKey('route.route_id'), primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('user.user_id'), primary_key=True) ) class User(db.Model): user_id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(255), unique=True) routes = db.relationship("Route", secondary=user_routes) def __repr__(self): return '&lt;User %r&gt;' % (self.token) class Route(db.Model): route_id = db.Column(db.Integer, primary_key=True) route_from = db.Column(db.String(100)) route_to = db.Column(db.String(100)) date_time = db.Column(db.DateTime) free_seats = db.Column(db.Integer) users = db.relationship("User", secondary=user_routes) def __repr__(self): return '&lt;Route %r&gt;' % (self.route_id) </code></pre>
0
2016-07-29T08:57:30Z
38,657,544
<p>After hours. I found solution <code>Association Object</code>.</p> <pre><code>from app import db class User_has_route(db.Model): __tablename__ = 'user_has_route' route_id = db.Column(db.Integer, db.ForeignKey('route.route_id'), primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), primary_key=True) tarif = db.Column(db.String(30)) route = db.relationship("Route", back_populates="users") user = db.relationship("User", back_populates="routes") class User(db.Model): __tablename__ = 'user' user_id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(255), unique=True) routes = db.relationship("User_has_route", back_populates="user") def __repr__(self): return '&lt;Userik %r&gt;' % (self.token) class Route(db.Model): __tablename__ = 'route' route_id = db.Column(db.Integer, primary_key=True) route_from = db.Column(db.String(100)) route_to = db.Column(db.String(100)) date_time = db.Column(db.DateTime) free_seats = db.Column(db.Integer) users = db.relationship("User_has_route", back_populates="route") def __repr__(self): return '&lt;Route %r&gt;' % (self.date_time) </code></pre>
0
2016-07-29T11:20:21Z
[ "python", "sqlalchemy", "many-to-many" ]
Minimalist Python Server for Unity3d 5.x
38,654,628
<p>TL;DR: I'm having trouble communicating between a Unity3D client app and a UDP python listener on the server.</p> <p>I'm trying to simply get a low-level call-and-response from a Unity3D game client via Unity 5.x NetworkTransport LLAPI and Python 3.x socket module</p> <p>Goal: Bounce the message sent to the server back to the client.</p> <p>Problem:</p> <ul> <li>The socket opens and the server prints a new recvfrom data every second when I run the Unity3d client, but unity never receives the bounced data.</li> <li>After ~10sec, the client receives a Timeout error along with a DisconnectEvent.</li> </ul> <p>Status:</p> <p>Client: Unity 5.4</p> <p>Server: Amazon AWS, port 8888 open</p> <p>Server-side python app:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 8888)) print ('Listening on port 8888') while True: data, addr = s.recvfrom(4096) if data: for i in range(0, len(data)): print (data[i]) print (data, addr) s.sendto(data, addr) </code></pre> <p>Client-side Unity networking class:</p> <pre><code>using UnityEngine; using UnityEngine.Networking; using System.Collections; public class NetworkExecutor : MonoBehaviour { const string addr = IP_ADDR; const int port = PORT; bool connected = false; // Doing lots of error checks but no need to save them. Let's def this and hold onto it. byte e; void Start () { // Some testing involves waiting for responses or repetitious send/receive calls. // We do this in coroutines for both efficiency and human sanity. StartCoroutine(TestNetwork()); } IEnumerator TestNetwork() { // Define network configurations. ConnectionConfig config = new ConnectionConfig(); int reliableChannel = config.AddChannel(QosType.Reliable); int maxConnections = 10; HostTopology hostTopo = new HostTopology(config, maxConnections); // Initialize and connect network with config. NetworkTransport.Init(); int hostId = NetworkTransport.AddHost(hostTopo); int connectionId = NetworkTransport.Connect(hostId, addr, port, 0, out e); Debug.Log("&lt;b&gt;Connect.&lt;/b&gt; Host ID: " + hostId + " Connection ID: " + connectionId); ErrStr(e); // Send test message. byte[] msg = System.Text.Encoding.UTF8.GetBytes("Send string"); NetworkTransport.Send(hostId, connectionId, reliableChannel, msg, 4096, out e); Debug.Log("&lt;b&gt;Send.&lt;/b&gt; Msg: " + msg); ErrStr(e); // Receive test message. int recHostId; int recConnectionId; int recChannelId; int recSize; msg = System.Text.Encoding.UTF8.GetBytes("Unmodified byte buffer."); NetworkEventType eventType = NetworkTransport.Receive(out recHostId, out recConnectionId, out recChannelId, msg, 4096, out recSize, out e); Debug.Log("&lt;b&gt;Receive.&lt;/b&gt; Type: " + eventType + " Msg: " + System.Text.Encoding.UTF8.GetString(msg)); Debug.Log("(hID:" + recHostId + " cID:" + recConnectionId + " chId:" + recChannelId + " " + recSize + ")"); ErrStr(e); NetworkTransport.Disconnect(hostId, connectionId, out e); ErrStr(e); yield break; } string ErrStr(byte e) { switch ((NetworkError)e) { case NetworkError.Ok: return "Ok"; case NetworkError.WrongHost: return "&lt;color=red&gt;Wrong Host&lt;/color&gt;"; case NetworkError.WrongConnection: return "&lt;color=red&gt;Wrong Connection&lt;/color&gt;"; case NetworkError.WrongChannel: return "&lt;color=red&gt;Wrong Channel&lt;/color&gt;"; case NetworkError.NoResources: return "&lt;color=red&gt;No Resources&lt;/color&gt;"; case NetworkError.BadMessage: return "&lt;color=red&gt;Bad Message&lt;/color&gt;"; case NetworkError.Timeout: return "&lt;color=red&gt;Timeout&lt;/color&gt;"; case NetworkError.MessageToLong: return "&lt;color=red&gt;Message Too Long&lt;/color&gt;"; case NetworkError.WrongOperation: return "&lt;color=red&gt;Wrong Operation&lt;/color&gt;"; case NetworkError.VersionMismatch: return "&lt;color=red&gt;Version Mismatch&lt;/color&gt;"; case NetworkError.CRCMismatch: return "&lt;color=red&gt;CRC Mismatch&lt;/color&gt;"; case NetworkError.DNSFailure: return "&lt;color=red&gt;DNS Failure&lt;/color&gt;"; default: return "&lt;color=red&gt;&lt;b&gt;Big problem, we don't know this error code.&lt;/b&gt;&lt;/color&gt;"; } } } </code></pre> <p>** Forgive the mess. Against my natural urges, many coding conventions and good practices are ignored here. This is because the app only serves the purpose of understanding Unity's and Python's most basic low-level networking usage. When a primitive semaphore can be established, this will be discarded and rewritten properly.</p>
0
2016-07-29T08:57:45Z
38,657,131
<p><code>UDP</code> and <code>TCP</code> are both standard protocol. This means that no matter what programming language you use, they should be able to communicate with each other.</p> <p>Your python code is using standard UDP code. Your Unity code is <strong>not</strong>. The <code>NetworkTransport</code> API you used is only made for communication between two Unity applications. It is an LLAPI library which is a tin layer built on of UDP. Again, it is <strong>not</strong> meant to be used for connection between Unity and a standard UDP connection, but between two Unity programs.</p> <p>To communicate with your python UDP code, you must use the <a href="https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient(v=vs.110).aspx" rel="nofollow"><code>UdpClient</code></a> class from the <code>System.Net.Sockets</code> namespace, in your C# code. Here is an <a href="http://stackoverflow.com/q/37131742/3785314">example</a> of a UDP code in Unity.</p>
1
2016-07-29T10:59:00Z
[ "c#", "python", "unity3d" ]
How to convert large list of dictionary to dataframe/matrix
38,654,677
<p>I have a list of dictionaries which has about 5 million lines.<br> The list looks like this:</p> <pre><code>[{"a":100, "b":50},{"c":2,"a":10}] </code></pre> <p>What I want is a dataframe or matrix like this: </p> <pre><code>a b c 100 50 0 10 0 2 </code></pre> <p>Then I will feed it into a cluster algorithm. </p> <p>The <code>pd.DataFrame(list)</code> works fine when the list is not large. But the list I got can not fit into memory. </p> <p>I tried to turn the list into spase matrix, but still, memory error accured when doing kmeans. </p> <p>So is there a way to create a huge matrix from the list, for example write to hard drive line by line? In this case, I can read this huge matrix line by line from hard drive, and then doing kmeans.</p> <p>Thanks a lot</p>
-1
2016-07-29T09:00:06Z
38,654,853
<p>Should you not use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow"><code>df.from_dict</code></a> ?</p> <p>To feed into a cluster algorithm you could convert the resulting numeric columns into a numpy array:</p> <pre><code># convert the numeric cols into a two-dimensional numpy array # will cast the columns into a numpy array in the form of Tuples numpy_array = df.as_matrix(columns = ['col_one', 'col_two']) </code></pre>
0
2016-07-29T09:09:04Z
[ "python", "pandas" ]
How to convert large list of dictionary to dataframe/matrix
38,654,677
<p>I have a list of dictionaries which has about 5 million lines.<br> The list looks like this:</p> <pre><code>[{"a":100, "b":50},{"c":2,"a":10}] </code></pre> <p>What I want is a dataframe or matrix like this: </p> <pre><code>a b c 100 50 0 10 0 2 </code></pre> <p>Then I will feed it into a cluster algorithm. </p> <p>The <code>pd.DataFrame(list)</code> works fine when the list is not large. But the list I got can not fit into memory. </p> <p>I tried to turn the list into spase matrix, but still, memory error accured when doing kmeans. </p> <p>So is there a way to create a huge matrix from the list, for example write to hard drive line by line? In this case, I can read this huge matrix line by line from hard drive, and then doing kmeans.</p> <p>Thanks a lot</p>
-1
2016-07-29T09:00:06Z
38,655,094
<p>If the list doesn't fit in memory, you could loop through your list chunk by chunk (full disclosure: I don't know how slow/fast this solution is):</p> <pre><code>import pandas as pd tmp = [] chunksize = 100 df = pd.DataFrame() for j, item in enumerate(mylist): tmp.append(item) if j % chunksize == chunksize-1: df2 = pd.DataFrame(tmp) df = pd.concat([df, df2], ignore_index=True) tmp = [] df2 = pd.DataFrame(tmp) df = pd.concat([df, df2], ignore_index=True) </code></pre>
0
2016-07-29T09:21:18Z
[ "python", "pandas" ]
Django settings module not found
38,654,683
<h1>background</h1> <p>I'm trying to split my settings by environment by following <a href="http://stackoverflow.com/a/15325966/766570">these instructions</a>.</p> <p>Now I would like to simply run my test command like so:</p> <pre><code>./run ./manage.py test --settings=bx.settings.local </code></pre> <p>currently the following line</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bx.settings") </code></pre> <p>is available in these files</p> <pre><code>manage.py wsgi.py </code></pre> <p>and so i removed it (since it's supposed to be read from the command line instead).</p> <p>I also created a <code>settings</code> folder inside my <code>bx</code> app and added the files</p> <pre><code>__init__.py base.py local.py </code></pre> <p>to it. <hr></p> <h1>notes</h1> <p>note: the <code>run</code> file is this:</p> <pre><code>#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )" docker run \ --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ --link beneple_db:db \ -v $DIR:/beneple \ -t -i --rm \ beneple/beneple \ $@ </code></pre> <p><hr></p> <h1>problem</h1> <p>when i run the command </p> <pre><code>./run ./manage.py test --settings=bx.settings.local </code></pre> <p>I get this error</p> <pre><code> File "/beneple/bx/org/serializers.py", line 10, in &lt;module&gt; from bx.settings import DOMAIN ImportError: cannot import name DOMAIN </code></pre> <p>in serializers.py:10, we got this</p> <pre><code>from bx.settings import DOMAIN </code></pre> <p>so i replaced <code>bx.settings</code> with </p> <pre><code>from django.conf import settings from settings import DOMAIN </code></pre> <p>and instead i got this error:</p> <pre><code> File "/beneple/bx/org/serializers.py", line 12, in &lt;module&gt; from settings import DOMAIN ImportError: No module named settings </code></pre> <hr> <h1>debugging</h1> <p>the weird part is that if i put a breakpoint after <code>from django.conf import settings</code>, and type the following:</p> <pre><code>ipdb&gt; print(settings) &lt;Settings "bx.settings.local"&gt; ipdb&gt; settings.DOMAIN 'http://localhost:8000' </code></pre> <p>I'm confused why it's not recognizing settings here as a module?</p> <hr> <h1>update</h1> <p>I noticed that my templates directory changed. In my settings file I have</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .. TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR, 'templates')],.. </code></pre> <p>However notice the difference in the value of <code>settings.TEMPLATES[0]['DIRS'] </code> between the old way and new way:</p> <p><em>old way</em>:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bx.settings") ['/beneple/templates'] </code></pre> <p><em>new way</em>:</p> <pre><code>./run ./manage.py test --settings=bx.settings.local ['/beneple/bx/templates'] </code></pre> <p>why is this the case? and how do I (programmatically) make the new way output the same result as the old one?</p>
0
2016-07-29T09:00:30Z
38,654,785
<p>Once you've imported settings from <code>django.conf</code>, you mustn't import again from settings; you already have the settings object, you can just refer to <code>settings.DOMAIN</code> directly.</p>
1
2016-07-29T09:05:18Z
[ "python", "django", "python-2.7", "unit-testing", "django-settings" ]
Django settings module not found
38,654,683
<h1>background</h1> <p>I'm trying to split my settings by environment by following <a href="http://stackoverflow.com/a/15325966/766570">these instructions</a>.</p> <p>Now I would like to simply run my test command like so:</p> <pre><code>./run ./manage.py test --settings=bx.settings.local </code></pre> <p>currently the following line</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bx.settings") </code></pre> <p>is available in these files</p> <pre><code>manage.py wsgi.py </code></pre> <p>and so i removed it (since it's supposed to be read from the command line instead).</p> <p>I also created a <code>settings</code> folder inside my <code>bx</code> app and added the files</p> <pre><code>__init__.py base.py local.py </code></pre> <p>to it. <hr></p> <h1>notes</h1> <p>note: the <code>run</code> file is this:</p> <pre><code>#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )" docker run \ --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ --link beneple_db:db \ -v $DIR:/beneple \ -t -i --rm \ beneple/beneple \ $@ </code></pre> <p><hr></p> <h1>problem</h1> <p>when i run the command </p> <pre><code>./run ./manage.py test --settings=bx.settings.local </code></pre> <p>I get this error</p> <pre><code> File "/beneple/bx/org/serializers.py", line 10, in &lt;module&gt; from bx.settings import DOMAIN ImportError: cannot import name DOMAIN </code></pre> <p>in serializers.py:10, we got this</p> <pre><code>from bx.settings import DOMAIN </code></pre> <p>so i replaced <code>bx.settings</code> with </p> <pre><code>from django.conf import settings from settings import DOMAIN </code></pre> <p>and instead i got this error:</p> <pre><code> File "/beneple/bx/org/serializers.py", line 12, in &lt;module&gt; from settings import DOMAIN ImportError: No module named settings </code></pre> <hr> <h1>debugging</h1> <p>the weird part is that if i put a breakpoint after <code>from django.conf import settings</code>, and type the following:</p> <pre><code>ipdb&gt; print(settings) &lt;Settings "bx.settings.local"&gt; ipdb&gt; settings.DOMAIN 'http://localhost:8000' </code></pre> <p>I'm confused why it's not recognizing settings here as a module?</p> <hr> <h1>update</h1> <p>I noticed that my templates directory changed. In my settings file I have</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .. TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR, 'templates')],.. </code></pre> <p>However notice the difference in the value of <code>settings.TEMPLATES[0]['DIRS'] </code> between the old way and new way:</p> <p><em>old way</em>:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bx.settings") ['/beneple/templates'] </code></pre> <p><em>new way</em>:</p> <pre><code>./run ./manage.py test --settings=bx.settings.local ['/beneple/bx/templates'] </code></pre> <p>why is this the case? and how do I (programmatically) make the new way output the same result as the old one?</p>
0
2016-07-29T09:00:30Z
38,654,815
<p><code>from settings import DOMAIN</code> tries to load module <code>settings</code> from <code>PYTHONPATH</code>, not from the module you already imported.</p> <p>You could just do the following: <code>DOMAIN = settings.DOMAIN</code></p>
1
2016-07-29T09:06:50Z
[ "python", "django", "python-2.7", "unit-testing", "django-settings" ]
Preserving the (non-alphabetical) order of data sets or groups when saving to .hdf5
38,654,797
<p>I have some raw data that I would like to store in .hdf5 file format together with the results I get from the analysis of the data. Before saving the data to disk I sort the different data sets in a way that is meaningful to me, using time. One example of this could be that the data sets are sorted like this: ['50us','100us','200us','5ns','20ns','500ns'] - I generally sort the data with increasing time. </p> <p>The problem is that when saving the data to the .hdf5 data sets are sorted alphabetically. To confirm this, I made this minimal working example:</p> <pre><code>with h5py.File(destination_folder+'\debugging.hdf5', 'w') as f: alphabet_example = ['zz9999', 'zz8888','aaaa9999','ZZ9999'] for name in alphabet_example: group_string = 'testing/'+ name f[group_string] = np.linspace(1,10,37) real_example = ['50us','100us','200us','5ns','20ns','500ns'] data_for_example = [1,2,3,4,5,6] for num, name in enumerate(real_example): group_string = 'real/'+ name f[group_string] = data_for_example[num] for names in f['testing/']: print(names) print('\n') for names in f['real/']: print(names) print(f['real/'+names].value) </code></pre> <p>I would save me so much developing and executing times if the data sets (and groups) could be stored in the order I save them. Otherwise I have to run a function sorting the data <strong>every time</strong> I load data from file - this goes for both analysis and plotting of the data. Right now I am using a list of the alphabeyt to preface each data set so they become 'a_50us', 'b_100us', 'c_200us' etc., but it is a bit embarrassing to use that kind of solution when you want to share the code and .hdf5 files with collaborators. </p> <p>I use windows 7, python 3.5 and h5py 2.6.0 if it matters :)</p> <p>Cheers!</p>
0
2016-07-29T09:05:56Z
38,666,005
<p>To my knowledge, this is not possible with h5py. However, it is possible using <a href="http://unidata.github.io/netcdf4-python/" rel="nofollow">netCDF4</a> (comes with the Anaconda distribution if you have that). HDF5 and NetCDF4 files are interoperable, so the resulting file will be able to be read later with h5py.</p>
1
2016-07-29T19:11:43Z
[ "python", "sorting", "python-3.x", "hdf5", "h5py" ]
program crashes if image is not found in the folder,but it should record in log- logging issue
38,654,806
<p>my program crashes if that particular image is not found in the image folder.The program looks for image in the image folder and imagecolumn in the csv.If the imagename is present in the imagecolumn but not found in the folder ,then it crashes. i tried to log the imagefile,but failed.</p> <p>This is I have so far</p> <pre><code>import pandas as pd import os import shutil # making a duplicate copy of a file import logging from os.path import splitext # splits name &amp; extension from a file class Image: def image_fix(self): # logging LOG = "example.log" logging.basicConfig(filename='example.log', filemode='w', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) # console handler console = logging.StreamHandler() console.setLevel(logging.ERROR) logging.getLogger("").addHandler(console) # using panda to open and read csv df = pd.read_csv('rgw.csv') df['Image'] = df.ImageName + "_" + df.ImageWChain + ".jpg" #checking if column "ImageWChain" has "jpg" extension,then concat .jpg if ".jpg" not in df.ImageWChain: df['ImageWChain'] = df.ImageWChain + ".jpg" if ".jpg" not in df.ImageName: df['ImageName'] = df.ImageName + ".jpg" # write to csv df.to_csv('rgw.csv') old_image = df.ImageName new_image = df.Image #splits the imagename and extension for item in enumerate(old_image): name, ext = splitext(old_image[item[0]]) if (ext == ""): continue oldFileName = name + ext print("oldFileName = " + oldFileName) newFileName = new_image print("newFileName = " + newFileName) #checks whether image file exits in folder or not if (os.path.isfile(oldFileName)): #creates duplicate copy of an image for old_image, new_image in zip(df.ImageName,df.Image): shutil.copy2(old_image,new_image) else: # if image not found in folder,then stores in log logging.info(oldFileName) # write into log logger = logging.getLogger(oldFileName) logger.debug(" &lt;- This image was not found in the folder") if __name__=="__main__": obj = Image() obj.image_fix() </code></pre> <p>The traceback is </p> <pre><code>C:\Python27\python.exe D:/New/a.py Traceback (most recent call last): File "D:/New/a.py", line 23, in &lt;module&gt; shutil.copy2(old_image,new_image) File "C:\Python27\lib\shutil.py", line 130, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory: 'R0056SS.jpg' </code></pre>
-1
2016-07-29T09:06:15Z
38,655,246
<p>Here :</p> <pre><code> #checks whether image file exits in folder or not if (os.path.isfile(oldFileName)): </code></pre> <p>You are testing the existence of <code>oldFileName</code>, but then trying to copy <code>old_image</code> :</p> <pre><code> #creates duplicate copy of an image for old_image, new_image in zip(df.ImageName,df.Image): shutil.copy2(old_image,new_image) </code></pre>
1
2016-07-29T09:28:20Z
[ "python", "logging" ]
What needs to be added in code to remove spaces in config file?
38,654,903
<p>i have a config file and when i write into it it has spaces in it</p>
0
2016-07-29T09:11:46Z
38,654,935
<p>Here is the definition of <code>RawConfigParser.write</code>:</p> <pre><code>def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self._defaults: fp.write("[%s]\n" % DEFAULTSECT) for (key, value) in self._defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) for (key, value) in self._sections[section].items(): if key != "__name__": fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") </code></pre> <p>As you can see, the <code>%s = %s\n</code> format is hard-coded into the function. I think your options are:</p> <ol> <li>Use the INI file with whitespace around the equals</li> <li>Overwrite <code>RawConfigParser</code>'s <code>write</code> method with your own</li> <li>Write the file, read the file, remove the whitespace, and write it again</li> </ol> <p>If you're 100% sure option 1 is unavailable, here's a way to do option 3:</p> <pre><code>def remove_whitespace_from_assignments(): separator = "=" config_path = "config.ini" lines = file(config_path).readlines() fp = open(config_path, "w") for line in lines: line = line.strip() if not line.startswith("#") and separator in line: assignment = line.split(separator, 1) assignment = map(str.strip, assignment) fp.write("%s%s%s\n" % (assignment[0], separator, assignment[1])) else: fp.write(line + "\n") </code></pre>
4
2016-07-29T09:13:29Z
[ "python", "python-2.7", "configparser" ]
InvalidClientSecretsError - df2gspread - Panda - Google Sheet
38,654,923
<p>I am a newbie with Python (started learning it 2 weeks ago) and I am struggling with this task. </p> <p>I am trying to export a data-frame from Panda to a Google Spreadsheet. Yet, after having followed all the necessary steps (<a href="https://github.com/maybelinot/df2gspread" rel="nofollow">https://github.com/maybelinot/df2gspread</a>) I keep on having the same error: </p> <blockquote> <p>InvalidClientSecretsError: ('Error opening file', 'C:\Users\ User/.gdrive_private', 'No such file or directory', 2)</p> </blockquote> <p>The code I am using is: </p> <pre><code>from df2gspread import df2gspread as d2g import pandas as pd spreadsheet = 'C:\Users\User\Google Drive\Marketing Team' wks = d2g.upload(df_all_daily_campaign_y, wks_name='Example worksheet') </code></pre> <p>Please don´t give anything for granted with me since I have very limited knowledge of this topic ! </p> <p>I have seen this question posted elsewhere on the internet, but with no posted answers! Any help would be greatly appreciated!</p>
0
2016-07-29T09:12:50Z
38,673,030
<p>The error is indicating that the necessary <strong>OAuth</strong> file that contains client secrets in <code>C:\Users\ User/.gdrive_private</code> cannot be found.</p> <p>Please check completeness of your <a href="https://developers.google.com/api-client-library/python/guide/aaa_client_secrets" rel="nofollow">Client Secrets</a>. As mentioned in the given documentation, </p> <blockquote> <p>That can be error prone, along with it being an incomplete picture of all the information that is needed to get OAuth 2.0 working, which requires knowing all the endpoints and configuring a Redirect Endpoint.</p> </blockquote> <p>More information and helpful codes can be found in <a href="https://github.com/google/consumer-surveys/tree/master/python/src" rel="nofollow">GitHub</a> and <a href="http://oauth2client.readthedocs.io/en/latest/_modules/oauth2client/clientsecrets.html" rel="nofollow">oauth2client.clientsecrets</a>.</p>
0
2016-07-30T10:48:19Z
[ "python", "google-app-engine", "google-spreadsheet", "google-drive-sdk" ]
Minimum System Requirements to run Recommendation in Predictionio
38,654,977
<p>I tried to have predictionio integrate with my app. I used recommendation Engine deployment as in <a href="http://docs.prediction.io/templates/recommendation/quickstart/" rel="nofollow">quick start</a> in Predictionio website. Faced lot of issues but able to build the engine. I tried to train the model using <code>pio train</code>. But it gave an error saying "<code>java.lang.StackOverflowError</code>". So it means memory is not enough in my server. Then I tried to increase the memory by using <code>pio train -- --driver-memory 5g --executor-memory 5g</code>. Still I am getting the same error (I am using 4 cores, 6GB RAM Ubuntu 14.04 server).</p> <p>SO I want to know what is the minimum server requirements have Predictionio. </p>
0
2016-07-29T09:15:29Z
38,655,441
<p>Minimum Requirements can be found in <a href="http://actionml.com/docs/pio_quickstart" rel="nofollow">here</a></p>
1
2016-07-29T09:37:32Z
[ "python", "apache-spark", "recommendation-engine", "data-science", "predictionio" ]
Different crawling behavior on Ubuntu and Windows
38,654,983
<p>This piece of code retrieves the content of a page of Google Movies:</p> <pre><code>import urllib2 f = urllib2.urlopen("https://www.google.com/movies?hl=fr&amp;tid=4f451a87a71bfa51&amp;date=0") print(f.read()) </code></pre> <p>It correctly contains the movies scheduled at this theater when I run the script on my Windows PC. But I tried to execute the script on 3 different Ubuntu servers, and every time the content returned is a well-formed page that says that there are no movies currently scheduled.</p> <p>Do you know what can cause this difference in behavior, of just 3 lines of code? I also tried urllib.urlopen and the output is the same.</p>
0
2016-07-29T09:15:50Z
38,655,256
<p>It has nothing to do with the OS itself, or with Python in general. I tried to access this URL from a Windows machine in a browser and also got something along the lines of "No films found" (used Google Translate as I don't speak French).</p> <p>I suspect this URL is location-sensitive. When you accessed it through your Windows machine it managed to find your location (actual location or an estimate based on your IP).</p> <p>When you tried to access it through your Linux machines, it couldn't determine your location (or it did, and decided that your location is "wrong") so it doesn't match any theater schedule.</p>
1
2016-07-29T09:29:07Z
[ "python", "urllib2", "urllib" ]
Multiprocessing, having issues
38,654,999
<p>I'm a fairly novice programmer and I'm putting my hand to multiprocessing for the first time. After running into the usual pickling errors I searched here and found Pathos was likely the best thing to use.</p> <p>The point of the application in full is it connects to a collection of servers with ssh, pulls data out and stores it into a database. It works great, but it would obviously be beneficial if it ran multiprocessing.</p> <p>The original function call looks like this:</p> <pre><code> devices = sq.sqlOperation("SELECT * from Devices") for device in devices: pullNewData(device) </code></pre> <p>In short, the SQL query gives me a list of dictionaries, I feed pullNewData() a dictionary for each record, it goes, connects, pulls everything through and updates the database.</p> <p>I'd rather not rewrite a few thousand lines of code, so I'm hoping adapting it will be easy: All of the following examples have:</p> <pre><code>from pathos.multiprocessing import ProcessingPool as Pool </code></pre> <p>At the top. I've tried:</p> <pre><code> devices = sq.sqlOperation("SELECT * from Devices") p = Pool(4) p.apipe(pullNewData, devices) </code></pre> <p>Which silently failed, even with a try/except round it</p> <pre><code> devices = sq.sqlOperation("SELECT * from Devices") p = Pool(4) p.map(pullNewData, devices) </code></pre> <p>Same, silent fail:</p> <p>However:</p> <pre><code> devices = sq.sqlOperation("SELECT * from Devices") p = Pool(4) for data in devices: p.apipe(pullNewData(data)) </code></pre> <p>worked but just went through each one serially.</p> <p>In my desperation I even tried putting it inside a list comprehension (which, yes, is horribly ugly, but at that point I'd have done anything)</p> <pre><code> devices = sq.sqlOperation("SELECT * from Devices") p = Pool(4) [ p.apipe(pullNewData(data)) for data in devices ] </code></pre> <p>So, how Would I do this? How would I have it fire off a new connection for each record in a parallel fashion?</p>
1
2016-07-29T09:16:24Z
38,658,400
<p>So trying <code>Pool(1)</code> showed me what issues it was having. I was calling other functions within both this file and other files which, due to the function being an entirely new process it had no idea about, so I had to put import statements for both the other modules and issue a</p> <pre><code>from thisModule import thisFunction </code></pre> <p>for other functions in the same file. Then after that I upped the pool and it worked perfectly using:</p> <pre><code>devices = sq.sqlOperation("SELECT * from Devices") p = Pool(4) p.map(pullNewData, devices) </code></pre> <p>Thanks, this was extremely helpful and very much a learning experience for me.</p> <p>It hadn't twigged to me that the new process wouldn't be aware of the import statements in the file that the function lived in, or the other functions. Oh well. Thanks very much to thebjorn for pointing me in the right direction.</p>
1
2016-07-29T12:04:31Z
[ "python", "pathos" ]
Merge columns in Pandas based on date criteria
38,655,042
<p>I have a dataframe like this</p> <pre><code>In[337]: df Out[337]: 2013 2014 2015 2013-01-31 0.705935 0.983307 0.714397 2013-05-31 0.492020 0.532103 0.897666 2013-09-30 0.187822 0.779611 0.774774 2014-01-31 0.789511 0.383665 0.353669 2014-05-31 0.347580 0.540767 0.732863 2014-09-30 0.382052 0.960596 0.917685 2015-01-31 0.106079 0.622926 0.302552 2015-05-31 0.282134 0.195239 0.968098 2015-09-30 0.185158 0.410412 0.048988 </code></pre> <p>I am trying to merge the data into a new column based on the year in the index. eg "for row 2014-09-30 select data from column '2014', 0.960596"</p> <pre><code>Out[345]: data 2013-01-31 0.705935 2013-05-31 0.492020 2013-09-30 0.187822 2014-01-31 0.383665 2014-05-31 0.540767 2014-09-30 0.960596 2015-01-31 0.302552 2015-05-31 0.968098 2015-09-30 0.048988 </code></pre> <p>Is there a way to neatly automate this with an if loop or otherwise?</p> <p>Thanks for your help!</p>
2
2016-07-29T09:18:40Z
38,655,271
<pre><code>import pandas as pd import datetime # reproduce test data &gt; df = pd.DataFrame([[datetime.date(2013,01,31), 0.1, 0.2, 0.3], [datetime.date(2014,01,31), 0.1, 0.2, 0.3], [datetime.date(2015,01,31), 0.1, 0.2, 0.3]], columns=['date', '2013', '2014', '2015']).set_index('date') &gt; df.index.name = None &gt; df 2013 2014 2015 2013-01-31 0.1 0.2 0.3 2014-01-31 0.1 0.2 0.3 2015-01-31 0.1 0.2 0.3 # extract year and use it as a key for the row object &gt; df.apply(lambda r: r[str(r.name.year)], axis=1) 2013-01-31 0.1 2014-01-31 0.2 2015-01-31 0.3 # create the desired dataframe &gt; df_new = pd.DataFrame(df.apply(lambda r: r[str(r.name.year)], axis=1), index=df.index, columns=['data']) &gt; df_new data 2013-01-31 0.1 2014-01-31 0.2 2015-01-31 0.3 </code></pre>
2
2016-07-29T09:29:53Z
[ "python", "pandas" ]
Merge columns in Pandas based on date criteria
38,655,042
<p>I have a dataframe like this</p> <pre><code>In[337]: df Out[337]: 2013 2014 2015 2013-01-31 0.705935 0.983307 0.714397 2013-05-31 0.492020 0.532103 0.897666 2013-09-30 0.187822 0.779611 0.774774 2014-01-31 0.789511 0.383665 0.353669 2014-05-31 0.347580 0.540767 0.732863 2014-09-30 0.382052 0.960596 0.917685 2015-01-31 0.106079 0.622926 0.302552 2015-05-31 0.282134 0.195239 0.968098 2015-09-30 0.185158 0.410412 0.048988 </code></pre> <p>I am trying to merge the data into a new column based on the year in the index. eg "for row 2014-09-30 select data from column '2014', 0.960596"</p> <pre><code>Out[345]: data 2013-01-31 0.705935 2013-05-31 0.492020 2013-09-30 0.187822 2014-01-31 0.383665 2014-05-31 0.540767 2014-09-30 0.960596 2015-01-31 0.302552 2015-05-31 0.968098 2015-09-30 0.048988 </code></pre> <p>Is there a way to neatly automate this with an if loop or otherwise?</p> <p>Thanks for your help!</p>
2
2016-07-29T09:18:40Z
38,655,281
<p>Assuming the dates are parsed you can do this:</p> <pre><code>df.apply(lambda row: row[str(row.name.year)], axis=1) </code></pre> <p><strong>Edit:</strong></p> <p>This was what I was looking for:</p> <pre><code>pd.Series( df.lookup( row_labels=df.index, col_labels=df.index.year.astype(str) ), index=df.index ) </code></pre> <p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html#pandas.DataFrame.lookup" rel="nofollow"><code>lookup</code></a> method gives you for each given row label the value at the corresponding column label. This function is heaps faster (if I resample the dataframe to hourly, the first method is timed with ~3.5s while the <code>lookup</code> method finishes in ~20ms).</p>
3
2016-07-29T09:30:12Z
[ "python", "pandas" ]
Is there a way of converting a string of 1's and 0's to its binary counterpart, i.e. not ASCII
38,655,061
<p>In Python I have learnt that creating ints like <code>0b01101101</code> will create a binary literal.</p> <p>Say I have a string data type of <code>"01101101"</code> is there a way to convert this to a binary literal?</p> <p>The example usage is that I am going to create a data packet slowly building up the byte with relivant pices of data (Setting bits according to variables). Once I have the string, I'll need to write raw binary over a serial connection.</p> <p>Is it possible to convert the string <code>"01101101"</code> to <code>0b01101101</code> so it is a binary literal.</p> <p>Another exammple of my target for this, if it helps. is so I can dynamically create the binary data on the fly without having do do massive bitwise operations, I see it simpler just to make up a string of 1's and 0's as I collate data then convert it to a binary literal. Of course if there is a better way to go about it, improvements would be gladly accepted. </p>
0
2016-07-29T09:19:35Z
38,655,136
<p>You can use argument <code>base</code> from string to int conversion:</p> <pre><code>int('01101101', base=2) # output : 109 # (and 109 in base 10 = 01101101 in base 2) </code></pre> <p>And reverse action, use <code>bin()</code> to create the string with a <code>0b</code> at the beginning:</p> <pre><code>bin(109) # output : '0b01101101' </code></pre>
1
2016-07-29T09:23:11Z
[ "python", "binary", "serial-port" ]
Is there a way of converting a string of 1's and 0's to its binary counterpart, i.e. not ASCII
38,655,061
<p>In Python I have learnt that creating ints like <code>0b01101101</code> will create a binary literal.</p> <p>Say I have a string data type of <code>"01101101"</code> is there a way to convert this to a binary literal?</p> <p>The example usage is that I am going to create a data packet slowly building up the byte with relivant pices of data (Setting bits according to variables). Once I have the string, I'll need to write raw binary over a serial connection.</p> <p>Is it possible to convert the string <code>"01101101"</code> to <code>0b01101101</code> so it is a binary literal.</p> <p>Another exammple of my target for this, if it helps. is so I can dynamically create the binary data on the fly without having do do massive bitwise operations, I see it simpler just to make up a string of 1's and 0's as I collate data then convert it to a binary literal. Of course if there is a better way to go about it, improvements would be gladly accepted. </p>
0
2016-07-29T09:19:35Z
38,655,150
<p>Note on terminology: a binary literal is a piece of text, normally appearing in source code, so I've shown code that results in the same text, in a string object. A binary literal <em>is not a number</em>, but it evaluates to a number in Python code, so I've also shown code to calculate that number. <code>0b01101101</code> and <code>109</code> are different literals (one binary, one decimal), but when evaluated they give exactly the same result, an integer equal to one hundred and nine.</p> <p>If you want to write the integer 109 as a single byte over a serial connection, then what you want to write is the single character with code 109, <em>not</em> a binary literal.</p> <pre><code>my_string = "01101101" my_binary_literal = "0b" + my_string my_string_converted_to_integer = int(my_string, 2) my_single_character = chr(my_string_converted_to_integer) assert my_single_character == 'm' </code></pre>
2
2016-07-29T09:23:55Z
[ "python", "binary", "serial-port" ]
Is there a way of converting a string of 1's and 0's to its binary counterpart, i.e. not ASCII
38,655,061
<p>In Python I have learnt that creating ints like <code>0b01101101</code> will create a binary literal.</p> <p>Say I have a string data type of <code>"01101101"</code> is there a way to convert this to a binary literal?</p> <p>The example usage is that I am going to create a data packet slowly building up the byte with relivant pices of data (Setting bits according to variables). Once I have the string, I'll need to write raw binary over a serial connection.</p> <p>Is it possible to convert the string <code>"01101101"</code> to <code>0b01101101</code> so it is a binary literal.</p> <p>Another exammple of my target for this, if it helps. is so I can dynamically create the binary data on the fly without having do do massive bitwise operations, I see it simpler just to make up a string of 1's and 0's as I collate data then convert it to a binary literal. Of course if there is a better way to go about it, improvements would be gladly accepted. </p>
0
2016-07-29T09:19:35Z
38,655,170
<p>There is: First convert it to an int and from there to a binary literal, like so <code>bin(int("01101101", base=2))</code></p>
1
2016-07-29T09:24:49Z
[ "python", "binary", "serial-port" ]