title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Testing ModelSerializers
39,180,100
<p>I am trying to learn the best way to test my serializers but having some issues. In the below example I am testing to see if creating new users works correctly. ie can hash the password. The error i am getting is:</p> <blockquote> <p>TypeError: create() missing 1 required positional argument: 'validated_data'</p> </blockquote> <p>Im not really sure what I need to pass in as <code>validated_data</code> </p> <p>serializers.py</p> <pre><code>class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'password') extra_kwargs = { 'url': {'view_name': 'user-detail'}, 'password': {'write_only': True} } def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): user = User.objects.get(id=instance.id) user.set_password(validated_data['password']) user.save() return user </code></pre> <p>tests.py</p> <pre><code>class UserSerializerTest(APITestCase): def setUp(self): factory = APIRequestFactory() request = factory.get(path=reverse('user-list')) self.serializer_context = { 'request': Request(request), } def test_create_user(self): from .serializers import UserSerializer data = {'username': 'temp_usr', 'email': 'temp@email.com', 'password': 'temp_pass'} user = UserSerializer(data=data, context=self.serializer_context).create() </code></pre>
0
2016-08-27T10:29:43Z
39,201,791
<p>You called <code>create</code> in your test. You should call <code>is_valid</code> and then <code>save</code>.</p> <pre><code>user = UserSerializer(data=data, context=self.serializer_context) user.is_valid(raise_exception=True) user.save() </code></pre>
0
2016-08-29T08:33:09Z
[ "python", "django", "django-rest-framework" ]
Python, bs4: Tags in inspection are nowhere to be found when parsing
39,180,183
<p>I run into an unexpected problem, I am using Python 3.5 and BeautifulSoup. I want to parse the following link:</p> <pre><code>url = 'https://www.leboncoin.fr/chaussures/627533472.htm?ca=16_s' import requests, bs4 res = requests.get(url) res.raise_for_status() DicoSoup = bs4.BeautifulSoup(res.text, "lxml") </code></pre> <p>I am interested in retrieving the link to the pictures that are in the offer. When I inspect the html of the website I found that there are to be found under the tag div with class 'thumbnails', they are under tag span with class 'item_imagePic', they are img tags</p> <p>However, when I select the div tag, the span tags are nowhere to be found:</p> <pre><code>div = DicoSoup.select("div.thumbnails") div Out[54]: [&lt;div class="thumbnails" data-alt="Talons aiguilles Stéphane Kélian - 37.5"&gt; &lt;ul&gt; &lt;li class="thumb selected trackable" data-info='{"event_name" : "ad_view::photos", "event_type" : "click", "click_type" : "N", "event_s2" : "2"}' id="thumb_0"&gt;&lt;/li&gt; &lt;li class="thumb trackable" data-info='{"event_name" : "ad_view::photos", "event_type" : "click", "click_type" : "N", "event_s2" : "2"}' id="thumb_1"&gt; &lt;/li&gt; &lt;li class="thumb trackable" data-info='{"event_name" : "ad_view::photos", "event_type" : "click", "click_type" : "N", "event_s2" : "2"}' id="thumb_2"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;] </code></pre> <p>When I inspect the html content, here is what I see:</p> <pre><code>&lt;div class="thumbnails" data-alt="Talons aiguilles Stéphane Kélian - 37.5" style="width: 596px;"&gt; &lt;ul style=""&gt; &lt;li id="thumb_0" class="thumb selected trackable" data-info="{&amp;quot;event_name&amp;quot; : &amp;quot;ad_view::photos&amp;quot;, &amp;quot;event_type&amp;quot; : &amp;quot;click&amp;quot;, &amp;quot;click_type&amp;quot; : &amp;quot;N&amp;quot;, &amp;quot;event_s2&amp;quot; : &amp;quot;2&amp;quot;}"&gt;&lt;span class="item_imagePic"&gt;&lt;img src="//img0.leboncoin.fr/thumbs/d89/d89c778e852e4a175d5d1ba96b2ec9c220445732.jpg" alt="Talons aiguilles Stéphane Kélian - 37.5"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li id="thumb_1" class="thumb trackable" data-info="{&amp;quot;event_name&amp;quot; : &amp;quot;ad_view::photos&amp;quot;, &amp;quot;event_type&amp;quot; : &amp;quot;click&amp;quot;, &amp;quot;click_type&amp;quot; : &amp;quot;N&amp;quot;, &amp;quot;event_s2&amp;quot; : &amp;quot;2&amp;quot;}"&gt;&lt;span class="item_imagePic"&gt;&lt;img src="//img1.leboncoin.fr/thumbs/7d9/7d9b62d9efd2187472dc16ca2794be1bbaeb1370.jpg" alt="Talons aiguilles Stéphane Kélian - 37.5"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li id="thumb_2" class="thumb trackable" data-info="{&amp;quot;event_name&amp;quot; : &amp;quot;ad_view::photos&amp;quot;, &amp;quot;event_type&amp;quot; : &amp;quot;click&amp;quot;, &amp;quot;click_type&amp;quot; : &amp;quot;N&amp;quot;, &amp;quot;event_s2&amp;quot; : &amp;quot;2&amp;quot;}"&gt;&lt;span class="item_imagePic"&gt;&lt;img src="//img2.leboncoin.fr/thumbs/288/28865002bb34bad516574bd1e9b42d2a2bb928f2.jpg" alt="Talons aiguilles Stéphane Kélian - 37.5"&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>How is it possible? What do I need to do to select them?</p> <p>I have tried:</p> <pre><code>div = DicoSoup.select_one("div.thumbnails span.item_imagePic") div = DicoSoup.select_one("div.thumbnails ul li span.item_imagePic") div = DicoSoup.select("div.thumbnails ul li span.item_imagePic") span = DicoSoup.find('span', {'class': 'item_imagePic'}) span = DicoSoup.find('span',id="thumb_0") div = DicoSoup.select("div.thumbnails img") div = DicoSoup.select("div.thumbnails span img") div = DicoSoup.select("div.thumbnails ul li span.item_imagePic img") </code></pre> <p>They all return me objects of type 'NoneType' </p> <p>Thanks,</p>
1
2016-08-27T10:39:36Z
39,180,247
<p>As I commented the thumbnails are dynamically generated using JS but you can get the script and parse the paths:</p> <pre><code>soup = BeautifulSoup(requests.get("https://www.leboncoin.fr/chaussures/627533472.htm?ca=16_s").content) script = soup.select_one("div.thumbnails").find_next("script") print(script.text.strip()) </code></pre> <p>That gives you:</p> <pre><code>var images = new Array(), images_thumbs = new Array(); images_thumbs[0] = "//img0.leboncoin.fr/thumbs/d89/d89c778e852e4a175d5d1ba96b2ec9c220445732.jpg"; images[0] = "//img0.leboncoin.fr/images/d89/d89c778e852e4a175d5d1ba96b2ec9c220445732.jpg"; images_thumbs[1] = "//img1.leboncoin.fr/thumbs/7d9/7d9b62d9efd2187472dc16ca2794be1bbaeb1370.jpg"; images[1] = "//img1.leboncoin.fr/images/7d9/7d9b62d9efd2187472dc16ca2794be1bbaeb1370.jpg"; images_thumbs[2] = "//img2.leboncoin.fr/thumbs/288/28865002bb34bad516574bd1e9b42d2a2bb928f2.jpg"; images[2] = "//img2.leboncoin.fr/images/288/28865002bb34bad516574bd1e9b42d2a2bb928f2.jpg"; </code></pre> <p>To get the images links:</p> <pre><code>import re soup = BeautifulSoup(requests.get("https://www.leboncoin.fr/chaussures/627533472.htm?ca=16_s").content) script = soup.select_one("div.thumbnails").find_next("script").text print(re.findall("images_thumbs\[\d+\]\s+=\s+\"(.*?)\";", script)) </code></pre> <p>Or just splitlines and strip:</p> <pre><code> [s.split("=", 1)[1].strip('"; ') for s in script.splitlines() if s.strip().startswith("images_thumbs")] </code></pre> <p>Both give you:</p> <pre><code>[u'//img0.leboncoin.fr/thumbs/d89/d89c778e852e4a175d5d1ba96b2ec9c220445732.jpg', u'//img1.leboncoin.fr/thumbs/7d9/7d9b62d9efd2187472dc16ca2794be1bbaeb1370.jpg', u'//img2.leboncoin.fr/thumbs/288/28865002bb34bad516574bd1e9b42d2a2bb928f2.jpg'] [u'//img0.leboncoin.fr/thumbs/d89/d89c778e852e4a175d5d1ba96b2ec9c220445732.jpg', u'//img1.leboncoin.fr/thumbs/7d9/7d9b62d9efd2187472dc16ca2794be1bbaeb1370.jpg', u'//img2.leboncoin.fr/thumbs/288/28865002bb34bad516574bd1e9b42d2a2bb928f2.jpg'] </code></pre> <p>Last all you need is to prepend the scheme which is <em>https</em>:</p> <pre><code> ["https://"+ path for path in re.findall("images_thumbs\[\d+\]\s+=\s+\"(.*?)\";", script)] </code></pre>
1
2016-08-27T10:47:55Z
[ "python", "parsing", "tags", "beautifulsoup" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,261
<p>You can use <a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">filter</a></p> <pre><code>&gt;&gt;&gt; mylist = [1,2,1,2,1,2,3,4,5,1,2,3] &gt;&gt;&gt; filter(lambda x:x!=2, mylist) [1, 1, 1, 3, 4, 5, 1, 3] </code></pre> <p>Or simple list comprehension.</p> <pre><code>my_list = [i for i in my_list if i!=2] </code></pre> <p>You can even use <code>remove()</code> to get the correct result by doing this:</p> <pre><code>&gt;&gt;&gt; while True: ... try: ... mylist.remove(2) ... except: ... break ... &gt;&gt;&gt; mylist [1, 1, 1, 3, 4, 5, 1, 3] </code></pre> <p>But, this is ugly, and often causes unexpected behavior. You should never modify a list while iterating. </p>
3
2016-08-27T10:49:37Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,278
<pre><code>mylist = [x for x in mylist if x != 2] </code></pre> <p>This is simpler than a filter.</p>
1
2016-08-27T10:51:20Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,279
<p>Using a list comprehension is probably the most pythonic way of doing this:</p> <pre><code>mylist = [number for number in mylist if number != 2] </code></pre> <p>This is because <code>list.remove(x)</code> only removes the first occurrence of <code>x</code> in the list. The above solution will create a new list based on <code>mylist</code> that will contain all elements of <code>mylist</code> if they are unequal to 2.</p>
1
2016-08-27T10:51:30Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,286
<p><a href="https://docs.python.org/3.5/tutorial/datastructures.html" rel="nofollow">According to docs</a>, this behavior is expected:</p> <blockquote> <p><code>list.remove(x)</code></p> <p><strong>Remove the first item from the list whose value is x</strong>. It is an error if there is no such item.</p> </blockquote> <p>To remove all occurences of value from list you may use list comprehension:</p> <pre><code>seq = [1,2,1,2,1,2,3,4,5,1,2,3] seq = [value for value in seq in value != 2] </code></pre>
1
2016-08-27T10:52:03Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,363
<p>From python help:</p> <pre><code>help(list.remove) </code></pre> <p>you can get this explanation:</p> <blockquote> <p>L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present.</p> </blockquote> <p>You can achieve it by using list comprehension:</p> <pre><code>mylist = [x for x in mylist if x != 2] </code></pre> <p>It just create a new list according to your conditions.</p>
1
2016-08-27T11:00:15Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</p> <pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] [1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3] </code></pre> <p>How can i remove all the match ?</p>
0
2016-08-27T10:48:04Z
39,180,396
<p>another way(if you wont create new list):</p> <pre><code>while 2 in mylist: mylist.remove(2) </code></pre>
0
2016-08-27T11:04:25Z
[ "python", "python-2.7" ]
Finding solution of differential equation
39,180,301
<p>I want to find a root X of equation below</p> <p><a href="http://i.stack.imgur.com/CClq1.png" rel="nofollow"><img src="http://i.stack.imgur.com/CClq1.png" alt="equation"></a></p> <p>Given Ls is length of something,f is frequency, X is a function of frequency, tgn is group delay and λ_0 is free space wavelength. If you want to more details, you can reference this document at page 20.</p> <p><a href="https://cdn.rohde-schwarz.com/pws/dl_downloads/dl_application/00aps_undefined/RAC-0607-0019_1_5E.pdf" rel="nofollow">https://cdn.rohde-schwarz.com/pws/dl_downloads/dl_application/00aps_undefined/RAC-0607-0019_1_5E.pdf</a></p> <p>Anyway Ls, tgn and λ_0 these variables can be obtained first.</p> <p>Then how to find X in Python? Thanks!</p>
0
2016-08-27T10:53:49Z
39,202,795
<p>If you want to solve a differential equation, you need some initial state information. Then you can either write your own solver, simplest solution would probably be explicit euler, alternatively you can look into this:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html#scipy.integrate.odeint" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html#scipy.integrate.odeint</a></p>
0
2016-08-29T09:28:32Z
[ "python", "scipy", "differential-equations" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want to know is there any better way to do this. Suppose I have long string and no of split value is 10, then this is very long way. So I want to know a better way to arrange the split values. Thanks.... </p>
0
2016-08-27T10:57:03Z
39,180,411
<p>You can make use of both <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>, simply like this:</p> <pre><code>string = "week32_Aug_24_2016" order = (0, 3, 1, 2) parts = string.split('_') new_string = ' '.join(parts[i] for i in order) </code></pre> <p>Also, note that I renamed your variable <code>str</code> to <code>string</code> to avoid shadowing built-in <a href="https://docs.python.org/3/library/stdtypes.html#str" rel="nofollow"><code>str</code></a> class.</p>
4
2016-08-27T11:05:31Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want to know is there any better way to do this. Suppose I have long string and no of split value is 10, then this is very long way. So I want to know a better way to arrange the split values. Thanks.... </p>
0
2016-08-27T10:57:03Z
39,180,560
<pre><code>str = "week32_Aug_24_2016" wk = str.split('_') i=0; newstr=""; while(i&lt;len(wk)): newstr=newstr+wk[i]+" " i=i+1 print newstr </code></pre> <p><strong>Something like that. If you want to keep last string in the middle it can be done.</strong></p>
0
2016-08-27T11:20:54Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want to know is there any better way to do this. Suppose I have long string and no of split value is 10, then this is very long way. So I want to know a better way to arrange the split values. Thanks.... </p>
0
2016-08-27T10:57:03Z
39,180,655
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; string = "week32_Aug_24_2016" &gt;&gt;&gt; re.sub(r'_(.*)_(.*)_(.*)', r' \3 \1 \2', string) 'week32 2016 Aug 24' </code></pre>
0
2016-08-27T11:32:20Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want to know is there any better way to do this. Suppose I have long string and no of split value is 10, then this is very long way. So I want to know a better way to arrange the split values. Thanks.... </p>
0
2016-08-27T10:57:03Z
39,180,680
<p>You can make use str.split() and format() as well:</p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = "{} {} {} {}".format(wk[0], wk[3], wk[1], wk[2]) </code></pre>
0
2016-08-27T11:35:01Z
[ "python" ]
Storm missing resources folder when deploying JAR topology
39,180,503
<p>I'm trying to deploy a topology that uses a MultiLang Bolt (written in Python):</p> <pre><code>builder.setBolt("avro-parser", new AvroBolt(), 3).shuffleGrouping("main-kafka-spout"); builder.setBolt("nlp-analyzer", new NLPBolt("/python/analyzer/audio_parser.py"), 2).shuffleGrouping("avro-parser"); </code></pre> <p>I can submit the topology without problems, but checking the log files I see this error:</p> <pre><code>java.lang.RuntimeException: Error when launching multilang subprocess at org.apache.storm.utils.ShellProcess.launch(ShellProcess.java:89) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.task.ShellBolt.prepare(ShellBolt.java:131) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.executor$fn__7953$fn__7966.invoke(executor.clj:792) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.util$async_loop$fn__625.invoke(util.clj:482) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.run(AFn.java:22) [clojure-1.7.0.jar:?] at java.lang.Thread.run(Unknown Source) [?:1.8.0_91] Caused by: java.io.IOException: Cannot run program "/usr/bin/python" (in directory "/var/lib/storm/supervisor/stormdist/sintonea-topology-main-22-1472285031/resources"): error=2, No such file or directory at java.lang.ProcessBuilder.start(Unknown Source) ~[?:1.8.0_91] at org.apache.storm.utils.ShellProcess.launch(ShellProcess.java:82) ~[storm-core-1.0.1.jar:1.0.1] ... 5 more Caused by: java.io.IOException: error=2, No such file or directory at java.lang.UNIXProcess.forkAndExec(Native Method) ~[?:1.8.0_91] at java.lang.UNIXProcess.&lt;init&gt;(Unknown Source) ~[?:1.8.0_91] at java.lang.ProcessImpl.start(Unknown Source) ~[?:1.8.0_91] at java.lang.ProcessBuilder.start(Unknown Source) ~[?:1.8.0_91] at org.apache.storm.utils.ShellProcess </code></pre> <p>Of course, I've noticed that I don't have a "resources" folder in the specified log trace:</p> <blockquote> <p>/var/lib/storm/supervisor/stormdist/sintonea-topology-main-22-1472285031/resources</p> </blockquote> <p>If you do a "ls" command in that directory, you'll see it:</p> <pre><code>stormcode.ser stormconf.ser stormjar.jar </code></pre> <p>Why storm is not creating a resources folder in that directory? </p> <p>I have two resources folders inside src/main/resources: </p> <ul> <li>schema: contains avro scheme files</li> <li>python: contains the python code</li> </ul> <p>These folders are copied into the JAR in the root directory, instead of a /resources folder.</p> <p>How is that possible? I have an AvroBolt that is using an schema in this way and it's not giving any problem (tested with a DummyBolt instead of MultiLang Bolt):</p> <pre><code>_schema = parser.parse(getClass().getResourceAsStream("/schema/caller_request.avsc")); </code></pre> <p><strong>EDIT</strong></p> <p>I've moved my resources folder to </p> <blockquote> <p>baseDirectory.value / "multilang"</p> </blockquote> <p>After reading this:</p> <p><a href="http://storm.apache.org/releases/current/Creating-a-new-Storm-project.html" rel="nofollow">http://storm.apache.org/releases/current/Creating-a-new-Storm-project.html</a></p> <p>Now the resource folder is created and copied, but I'm still having the same issue:</p> <pre><code>Serializer Exception: /usr/bin/python: can't open file '/resources/python/analyzer/audio_parser.py': [Errno 2] No such file or directory </code></pre> <p><strong>EDIT 2</strong></p> <p>I've found a workaround (create two resources folders at different levels): </p> <ol> <li>Create a multilang/resources in the parent directory of src (one level up). Copy the python folder inside: {base-directory}/multilang/resources/python/*.py</li> <li>Leave intact the folder src/main/schema: {base-directory}/src/main/resources/schema/caller_request.avsc.</li> </ol> <p>And added this to my build.sbt:</p> <pre><code>unmanagedResourceDirectories in Compile += { baseDirectory.value / "multilang" } unmanagedClasspath in Compile += baseDirectory.value / "multilang" </code></pre> <p>And set up my ShellBot as (ignoring the word "resources" or "/" in path):</p> <pre><code>NLPBolt nlpBolt = new NLPBolt("python/analyzer/audio_parser.py"); </code></pre> <p>And:</p> <pre><code>_schema = parser.parse(getClass().getResourceAsStream("/schema/caller_request.avsc")); </code></pre> <p>It seems to work, but I don't like this solution. Any thoughts?</p> <p><strong>EDIT 3</strong></p> <p>By the way, this code:</p> <pre><code>import storm #from nltk.stem.snowball import SnowballStemmer from es_tagger import SpanishTagger config = utils.load_json('python/analyzer/data/config.json') class AudioParserBolt(storm.BasicBolt): </code></pre> <p>Produces the following error:</p> <pre><code>Serializer Exception: Traceback (most recent call last): File "python/analyzer/audio_parser.py", line 27, in &lt;module&gt; class AudioParserBolt(storm.BasicBolt): AttributeError: 'module' object has no attribute 'BasicBolt' </code></pre>
1
2016-08-27T11:15:31Z
39,184,888
<p>So, this is basically what I did to get it working:</p> <ol> <li>Create folder ${basedir}/multilang/resources --> copy python code inside.</li> <li>Remove python code from ${basedir}/src/main/resources and leave only the Avro schemes.</li> <li>Add to the build.sbt file:</li> </ol> <blockquote> <p>unmanagedResourceDirectories in Compile += { baseDirectory.value / "multilang" } unmanagedClasspath in Compile += baseDirectory.value / "multilang"</p> </blockquote> <ol start="4"> <li>Download storm.py from <a href="https://github.com/apache/storm/blob/master/storm-multilang/python/src/main/resources/resources/storm.py" rel="nofollow">https://github.com/apache/storm/blob/master/storm-multilang/python/src/main/resources/resources/storm.py</a> and copy/paste it into ${basedir}/multilang/resources/python folder.</li> <li>In the Python code, comment or remove any print instruction (provokes Java exceptions parsing the tuples because print writes into standard output).</li> <li>In case your Python process is a bit slow (mine is an NLP process and requires a little bit to setup the first time), tell your topology to wait a little more:</li> </ol> <blockquote> <p>config.put(Config.TOPOLOGY_SUBPROCESS_TIMEOUT_SECS, );</p> </blockquote> <ol start="7"> <li>And a lot of trial and error =)</li> </ol> <p>Any time you need to use an external file in your Python code, like a configuration file, call it like this (the parent directory will be the multilang/resources we created before):</p> <blockquote> <p>config = utils.load_json('python/analyzer/data/config.json')</p> </blockquote>
1
2016-08-27T19:23:08Z
[ "java", "python", "sbt", "apache-storm" ]
Textblob module in python is not working for me
39,180,551
<p>Here is the code...</p> <pre><code>import textblob While True: print("Ok...") print("Enter the text....") text = input() blob = textblob.TextBlob(text) blob.translate(to = "de") </code></pre> <p>It ask for text and then tells me Nothing. Any help is appreciated! </p>
-1
2016-08-27T11:20:05Z
39,181,558
<p>Here's a working example:</p> <pre><code>import textblob while True: text = input("Which text you want to translate:") blob = textblob.TextBlob(text) print("--&gt; {0}".format(blob.translate(to = "de"))) </code></pre> <p>You forgot to print the German translated string</p>
1
2016-08-27T13:16:00Z
[ "python" ]
How to display parent table columns in django template
39,180,566
<p>I have two models in django as below:</p> <pre><code>class Directorates(models.Model): entrydate = models.DateTimeField(auto_now=True) directoratename = models.CharField("Directorate", max_length=1000) note = models.CharField("Note", max_length=2000, null=True) insertedby = models.IntegerField(null=False) updatedby = models.IntegerField(null=False, default='0') deletedby = models.IntegerField(null=False, default='0') def __str__(self): return self.directoratename class Departments(models.Model): entrydate = models.DateTimeField(auto_now=True) departmentname = models.CharField("Department", max_length=1000) note = models.CharField("Note", max_length=2000, null=True) directorate = models.ForeignKey(Directorates, on_delete=models.CASCADE) insertedby = models.IntegerField(null=False) updatedby = models.IntegerField(null=False, default='0') deletedby = models.IntegerField(null=False, default='0') def __str__(self): return self.departmentname </code></pre> <p>What I want to do is to display id, departmentname, note from Departments model and directoratename from Directorates model in a table in template.</p> <p>Below is my query which needs to be edited to meet the requirements.</p> <pre><code> Departments.objects.filter(deletedby=0).values("id", "departmentname", "note", "directorate_id").order_by('-id')[:5] </code></pre> <p>Below is the code for table population.</p> <pre><code>{% for d in data %} &lt;tr&gt; &lt;td&gt;{{ d.departmentname }}&lt;/td&gt; &lt;td&gt;directoratename to be displayed here.....&lt;/td&gt; &lt;td&gt;{{ d.note }}&lt;/td&gt; &lt;td class="pull-right"&gt; &lt;form action="{% url 'app:departments-delete' d.id %}" method="post"&gt; {% csrf_token %} &lt;div class="btn-group" role="group" aria-label="..."&gt; &lt;a href="{% url 'app:departments-edit' d.id %}" class="btn btn-warning glyphicon glyphicon-pencil"&gt;&lt;/a&gt; &lt;button type="submit" class="btn btn-danger glyphicon glyphicon-trash"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>I searched google to find the solution for this however I couldn't find any solution for this. Please help me.</p>
0
2016-08-27T11:21:34Z
39,181,113
<p>You're making things harder for yourself by using a <code>values()</code> query. Just pass the objects themselves:</p> <pre><code>departments = Departments.objects.filter(deletedby=0) </code></pre> <p>and now you can do:</p> <pre><code>{% for d in data %} &lt;tr&gt; &lt;td&gt;{{ d.departmentname }}&lt;/td&gt; &lt;td&gt;{{ d.directorate.directoratename }}&lt;/td&gt; </code></pre> <p>Note that you can make this more efficient by using <code>select_related</code> in the original query:</p> <pre><code>departments = Departments.objects.filter(deletedby=0).select_related('directorate') </code></pre> <p>Also note that it is normal in Django to give the models singular names - Department, Directorate - because an instance refers to a single one.</p>
0
2016-08-27T12:24:05Z
[ "python", "django", "django-models", "django-forms", "django-templates" ]
SQLAlchemy Build selectable query with multiple tables
39,180,608
<p>I created a materialized view for my flask web application with the help of <a href="http://www.jeffwidman.com/blog/847/using-sqlalchemy-to-create-and-manage-postgresql-materialized-views/" rel="nofollow">Jeff Widman</a>.</p> <p>Unfortunately he only describe how to join two tables. I would like to create a materialized view with more than two tables.</p> <pre><code>class AnalyticV(MaterializedView): __table__ = create_mat_view("my_view", db.select([Table1.id.label('id'), Table1.title.label('title'), Table2.location.label('loc'), Table3.time.label('time'),] ).select_from(db.join(Table1, Table2, isouter=True) ) ) </code></pre> <p>How can I insert a second </p> <pre><code>select_from(db.join(Table1, Table3, isouter=True)) </code></pre> <p>Table1 has two relationships to Table2 and Table3</p> <p>The SQL should look like this:</p> <pre><code>SELECT Table1.id AS id, Table1.title AS title, Table2.location AS loc, Table3.time AS time FROM Table1 LEFT OUTER JOIN Table2 ON Table2.id = Table1.table2_id LEFT OUTER JOIN Table3 ON Table3.id = Table1.table3_id </code></pre>
2
2016-08-27T11:26:47Z
39,182,008
<p>Just add another join</p> <pre><code>select_from(db.join(Table1, Table2, isouter=True).join(Table3, isouter=True)) </code></pre>
1
2016-08-27T14:04:06Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32, in module ImportError: No module named 'cryptography' </code></pre> <p>I installed pycrypto-2.6.1.win but the problem persist. Any help ?</p>
1
2016-08-27T11:26:48Z
39,180,737
<p>It's not <a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow">pycrypto</a> the package you need in order to import paramiko, try this:</p> <blockquote> <p>pip install <a href="https://pypi.python.org/pypi/paramiko/" rel="nofollow">paramiko</a></p> </blockquote>
2
2016-08-27T11:41:22Z
[ "python", "windows", "paramiko" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32, in module ImportError: No module named 'cryptography' </code></pre> <p>I installed pycrypto-2.6.1.win but the problem persist. Any help ?</p>
1
2016-08-27T11:26:48Z
39,180,780
<p>You need to install the <a href="https://pypi.python.org/pypi/cryptography" rel="nofollow">cryptography module</a>.</p> <p>Normally, dependencies would've automatically got pulled in when you install paramiko using a package manager like pip. How did you install paramiko? Are you installing manually? </p>
0
2016-08-27T11:46:03Z
[ "python", "windows", "paramiko" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32, in module ImportError: No module named 'cryptography' </code></pre> <p>I installed pycrypto-2.6.1.win but the problem persist. Any help ?</p>
1
2016-08-27T11:26:48Z
39,194,068
<p>It turned out that it was a proxy problem. It was blocking download. I did </p> <pre><code>pip install cryptography pip install paramiko </code></pre> <p>from a direct internet connection and it worked. Thanks everyone !</p>
0
2016-08-28T17:38:42Z
[ "python", "windows", "paramiko" ]
Loop through array stops increasing index (Orig: Message widget text randomly not refreshing)
39,180,689
<p>I have an automatically generated report in txt file that gets update every 5 or so seconds and looks like this:</p> <pre><code>Report Data Start Time:;00:00 25/08/2016Report;Va1;Val2;Val3;Val4;Val5;Val6;Val7 X;6;4;0;0;32;3;0.8125 Y;2;1;0;0;0;0;0 Z;5;1;0;0;0;0;0 [empty last line] </code></pre> <p>In tkinter, I created a GUI that would read the data and display it in real time in a sort of a table. The widgets are generated procedurally and stored in a collection under a predefined name, later they are called based on this name and their content modified. However when the data is read and put into the widgets some cells, seemingly at random, are empty. When I say randomly, it is actually pretty consistent (col2, row2 and col5 to 7, row2 to 3) BUT when I change the report file somehow, the new value may or may not appear (this really is very random).</p> <p>(Significantly) shortened version of the code with the same problem here:</p> <pre><code>import tkinter as tk class MainApplication(tk.Frame): global SkillWidgets SkillWidgets = {} def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.create_stuff() self.refresh() def create_stuff(self): screen_width = tkGUI.winfo_screenwidth() screen_height = tkGUI.winfo_screenheight() iSW = screen_width/1000 iSH = screen_height/1000 tkFrSkills = tk.Frame(tkGUI) tkFrSkills.place(x=(100*iSW)+20, y=20+(50*iSH), bordermode=tk.INSIDE, height=screen_height/2-(100+50*iSH), width=screen_width) for iRow in range(1,4): for iCol in range(1,8): tkMsg = tk.Message(tkFrSkills, text="", font=("Arial", 36), relief = tk.GROOVE, bd = 2, width = 100) tkMsg.place (x=((iCol-1)*100*iSW), y=(75*iRow*iSH)-(75*iSH), bordermode=tk.INSIDE, width = 100*iSW, height = 75*iSH) SkillWidgets[(iRow,iCol)] = tkMsg def refresh(self): fSkills = open("report.txt") sSkContents = fSkills.read() fSkills.close() SkLines = sSkContents.split("\n") del(SkLines[len(SkLines)-1]) iSkRow = 0 for sSkLine in SkLines: if "X" in sSkLine: iSkRow = 1 if "Y" in sSkLine: iSkRow = 2 if "Z" in sSkLine: iSkRow = 3 if iSkRow &gt; 0: SkItems = sSkLine.split(";") SkItems[1], SkItems[2], SkItems[3], SkItems[4] = SkItems[2], SkItems[4], SkItems[1], SkItems[3] SkItems[2] = str(int(SkItems[3])-int(SkItems[1])) del(SkItems[0]) ***print(SkLines[iSkRow]) for sSkItem in SkItems: iSkCol = SkItems.index(sSkItem)+1 ****print("Row=",iSkRow,"Col=",iSkCol,"sSkItem=",sSkItem) *****print("Row=",iSkRow,"Col=",iSkCol,"widget text =", SkillWidgets[(iSkRow,iSkCol)].cget("text")) SkillWidgets[(iSkRow,iSkCol)].config(text = sSkItem) ****print("Row=",iSkRow,"Col=",iSkCol,"sSkItem=",sSkItem) *****print("Row=",iSkRow,"Col=",iSkCol,"widget text =", SkillWidgets[(iSkRow,iSkCol)].cget("text")) print("----------") self.after(1000,self.refresh) if __name__ == "__main__": tkGUI = tk.Tk() tkGUI.attributes("-fullscreen", True) MainApplication(tkGUI).pack(side="top", fill="both", expand=True) tkGUI.mainloop() </code></pre> <p><strong>EDIT:</strong> I forgot to mention that I tried to print the values I am inputting (code adjusted - I highlighted the places with a number of asterisks</p> <p>*** this print gives correctly the relevant lines, however for some reason it runs through the cycle twice, giving</p> <pre><code>X;6;4;0;0;32;3;0.8125 Y;2;1;0;0;0;0;0 Z;5;1;0;0;0;0;0 </code></pre> <p>**** this print correctly gives out the value I want to input to the widget</p> <p>***** this print is getting to the root of the issue: a) if inputted value is to be "1", the loop does not go through 2:2 at all but gives only 2:1 twice and the first print shows the value of the widget as "1" (because I guess it went through 2:1 just before) b) if the inputted value is to be "2" and more, it works as intended - loop goes through 2:1, 2:2, 2:3 as expected</p> <p>(if value to be imputted = 1)</p> <pre><code>Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = 1 ---------- Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = 1 Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = 1 ---------- </code></pre> <p>if value to be imputted > 1</p> <pre><code>Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = Row= 2 Col= 1 sSkItem= 1 Row= 2 Col= 1 widget text = 1 ---------- Row= 2 Col= 2 sSkItem= 3 Row= 2 Col= 2 widget text = Row= 2 Col= 2 sSkItem= 3 Row= 2 Col= 2 widget text = 3 ---------- </code></pre> <p>c) in neither case does the loop go for rows 2&amp;3 through cols 5to7</p> <p><strong>EDIT2:</strong> Intriguing... now I added some more prints (nothing else though) and the value inputted into 2:2 being "1" does not seem to be a problem now (2:3 to 3:7 are still out of the loop though).</p> <p><strong>EDIT3:</strong> I seem to be getting to the cause... At this point, for row2 and row3, the, it simply stops increasing the index with the 5th iteration (item with index 4 is not loaded, instead item with index 3 is loaded again)</p> <pre><code> for sSkItem in SkItems: print(SkItems) print("item3: ", SkItems[3]) print("item4: ", SkItems[4]) print("item5: ", SkItems[5]) print("item6: ", SkItems[6]) iSkCol = SkItems.index(sSkItem) print("index", iSkCol) print("Row=",iSkRow,"Col=",iSkCol,"sSkItem=",sSkItem) print("Row=",iSkRow,"Col=",iSkCol,"widget text =", SkillWidgets[(iSkRow,iSkCol)].cget("text")) SkillWidgets[(iSkRow,(iSkCol))].config(text = sSkItem) print("Row=",iSkRow,"Col=",iSkCol,"sSkItem=",sSkItem) print("Row=",iSkRow,"Col=",iSkCol,"widget text =", SkillWidgets[(iSkRow,iSkCol)].cget("text")) </code></pre> <p>Resulting print-out reads as follows:</p> <pre><code>['1', 1, '2', '0', '0', '0', '0'] item3: 0 item4: 0 item5: 0 item6: 0 index 1 Row= 1 Col= 1 sSkItem= 1 Row= 1 Col= 1 widget text = Row= 1 Col= 1 sSkItem= 1 Row= 1 Col= 1 widget text = 1 --- ['1', 1, '2', '0', '0', '0', '0'] item3: 0 item4: 0 item5: 0 item6: 0 index 2 Row= 1 Col= 2 sSkItem= 2 Row= 1 Col= 2 widget text = Row= 1 Col= 2 sSkItem= 2 Row= 1 Col= 2 widget text = 2 --- ['1', 1, '2', '0', '0', '0', '0'] item3: 0 item4: 0 item5: 0 item6: 0 index 3 Row= 1 Col= 3 sSkItem= 0 Row= 1 Col= 3 widget text = Row= 1 Col= 3 sSkItem= 0 Row= 1 Col= 3 widget text = 0 --- ['1', 1, '2', '0', '0', '0', '0'] item3: 0 item4: 0 item5: 0 item6: 0 index 3 Row= 1 Col= 3 sSkItem= 0 Row= 1 Col= 3 widget text = 0 Row= 1 Col= 3 sSkItem= 0 Row= 1 Col= 3 widget text = 0 --- </code></pre>
0
2016-08-27T11:35:58Z
39,186,132
<p>I believe your problem lies in the incorrect use of the <code>for</code> loop, specifically</p> <pre><code>for sSkItem in SkItems: iSkCol = SkItems.index(sSkItem)+1 </code></pre> <p>Will give you index of <em>first occurence</em> of <code>sSkItem</code> in <code>SkItems</code> and NOT the index of current item from your loop as you no doubt expect/want. This will break if there are any duplicate items (as there are and as you observe).</p> <p>To fix that you can use your own counter to track the index for example:</p> <pre><code>currentIndex = 0 for sSkItem in SkItems: iSkCol = currentIndex currentIndex += 1 </code></pre> <p>Or use normal range for loop to iterate over <em>indexes</em> rather than items.</p>
0
2016-08-27T21:59:55Z
[ "python", "tkinter", "widget", "refresh" ]
speech_recognition module stuck in "say something" - python
39,180,695
<p>I am trying a python script for speech recognition, i have installed the required pyaudio and SpeechRecognition modules in my enivronment.</p> <p>The program was running fine till yesterday, but now it is stuck in "say something". Below is my code.</p> <pre><code>import speech_recognition as sr print "say something1" r = sr.Recognizer() print "say something2" with sr.Microphone() as source: # use the default microphone as the audio source print "say something3" audio = r.listen(source,timeout=3) # listen for the first phrase and extract it into audio data print "say something" try: print("You said " + r.recognize(audio)) # recognize speech using Google Speech Recognition except LookupError: # speech is unintelligible print("Could not understand audio") </code></pre> <p>Console o/p :-</p> <pre><code>say something1 say something2 ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slave ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave say something3 </code></pre> <p>Not duplicate of/ Have refferd to :- <a href="http://stackoverflow.com/questions/32005310/speech-recognition-python-code-not-working">speech recognition python code not working</a></p>
1
2016-08-27T11:36:53Z
39,189,620
<p>I have had the same problem with me, i ended up installing jack2d and pulseaudio and what not.</p> <p>That was the problem, I then uninstalled the jack2d by running </p> <pre><code>sudo apt-get remove --auto-remove jack </code></pre> <p>Then restarted the system, and then ran </p> <pre><code>jack_control stop </code></pre> <p>Then this will give the voice input to pulse-aduio.</p> <p>When you run the program, the console should print</p> <pre><code>ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slave ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map Cannot connect to server socket err = No such file or directory Cannot connect to server request channel jack server is not running or cannot be started JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock </code></pre> <p>The last lines state that Jack has stopped and the voice input is being redirected to pulse.</p> <p>what actually happening here is, the audio resoruce(mic) is being channeled only to either jack or pulse, so I uninstalled jack</p> <p>Now my program works just fine</p>
0
2016-08-28T09:05:55Z
[ "python", "python-2.7", "speech-recognition" ]
speech_recognition module stuck in "say something" - python
39,180,695
<p>I am trying a python script for speech recognition, i have installed the required pyaudio and SpeechRecognition modules in my enivronment.</p> <p>The program was running fine till yesterday, but now it is stuck in "say something". Below is my code.</p> <pre><code>import speech_recognition as sr print "say something1" r = sr.Recognizer() print "say something2" with sr.Microphone() as source: # use the default microphone as the audio source print "say something3" audio = r.listen(source,timeout=3) # listen for the first phrase and extract it into audio data print "say something" try: print("You said " + r.recognize(audio)) # recognize speech using Google Speech Recognition except LookupError: # speech is unintelligible print("Could not understand audio") </code></pre> <p>Console o/p :-</p> <pre><code>say something1 say something2 ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slave ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave say something3 </code></pre> <p>Not duplicate of/ Have refferd to :- <a href="http://stackoverflow.com/questions/32005310/speech-recognition-python-code-not-working">speech recognition python code not working</a></p>
1
2016-08-27T11:36:53Z
39,231,994
<p>When I tried your code as it is I got following <code>attribute</code> error.</p> <pre><code>AttributeError: 'Recognizer' object has no attribute 'recognize' </code></pre> <p>Upon going through <a href="https://pypi.python.org/pypi/SpeechRecognition/" rel="nofollow">documentation</a> it looks like the <code>Recognizer</code> class don't have a method <code>recognize</code>. you will need to use one of the several <code>recognize_*</code> methods that <code>recognize</code> class offers.<br> It seems you want to use <code>recognize_google</code>,so when I change your code from</p> <pre><code>print("You said " + r.recognize(audio)) </code></pre> <p>to</p> <pre><code>print("You said " + r.recognize_google(audio)) </code></pre> <p>The code is working for me. </p> <p>I said "hello", which was recognized below.</p> <pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; say something1 say something2 say something3 say something You said hello </code></pre> <p>Hope this helps.</p>
2
2016-08-30T15:47:22Z
[ "python", "python-2.7", "speech-recognition" ]
Product of two equals numpy arrays are different
39,180,779
<p>I'm facing very strange problem with arrays in python and numpy. First of all what Im trying to archive is : </p> <p>1) Get an MxN matrix from KxTxN matrix 2) Transpose this matrix and calculate product of this transposed matrix and the original one</p> <p>What I get is some what strange, here comes the code : </p> <p>First of all, I have read an image with help of cv2, and got K by T by 3 matrix (a field of RGB points), then I'm cutting a small window form it and reshaping this window to M by N matrix : </p> <pre><code>def clipSubwindowFromImage(img, i, j, winSize): winI = img[i - winSize: i + winSize + 1, j - winSize : j + winSize + 1, : ] res = np.vstack((winI[:,::3,:].reshape(winI.shape[1],3), winI[:,1::3,:].reshape(winI.shape[1],3), winI[:,2::3,:].reshape(winI.shape[1],3))) return res </code></pre> <p>so far so god, say we had <code>winSize = 1, i = 1, j = 1</code> and got a 9x3 matrix as a result: this matrix : </p> <pre><code>&gt;&gt; subWin = clipSubwindowFromImage(background12x12b, 1, 1, 1) &gt;&gt; [[201 199 187] [216 219 198] [226 228 207] [243 241 228] [240 244 221] [233 235 213] [239 238 220] [238 240 216] [233 235 211]] </code></pre> <p>Then I just want to get the product in question, like this : </p> <pre><code>&gt;&gt;r1 = subWin.T.dot(subWin) &gt;&gt;[[197 234 89] [234 65 163] [ 89 163 105]] </code></pre> <p>Well, it's not right, the right result should be : </p> <pre><code>&gt;&gt;[[477125 479466 438361] [479466 481857 440483] [438361 440483 402793]] </code></pre> <p>But if I initialize <code>subWin</code> manually like this : </p> <pre><code>&gt;&gt;subWin = np.array([[201, 199, 187], [216, 219, 198], [226, 228, 207], [243, 241, 228], [240, 244, 221], [233, 235, 213],[239, 238, 220], [238, 240, 216],[233, 235, 211]]) </code></pre> <p>I get right result. </p> <p>I can't get it, <code>subWin</code> is the SAME array in both cases (I checked it). Any ideas? </p>
0
2016-08-27T11:45:50Z
39,181,052
<p>As @Aguy said, your problem comes from the data-type of your array. The dot product of a uint8 array with an other uint8 array gives an array that is also uint8 hence the data-type is overflowed in your case. Here's an example that shows the effect of overflow on your values:</p> <pre><code>import numpy as np a = np.array([[201, 199, 187], [216, 219, 198], [226, 228, 207], [243, 241, 228], [240, 244, 221], [233, 235, 213],[239, 238, 220], [238, 240, 216],[233, 235, 211]]) b = a.T.dot(a) print b.dtype print b print "overflowed uint8 :" print b.astype(np.uint8) </code></pre> <p>Gives:</p> <pre><code>&gt;&gt;&gt; int64 &gt;&gt;&gt; [[477125 479466 438361] &gt;&gt;&gt; [479466 481857 440483] &gt;&gt;&gt; [438361 440483 402793]] &gt;&gt;&gt; overflowed uint8 : &gt;&gt;&gt; [[197 234 89] &gt;&gt;&gt; [234 65 163] &gt;&gt;&gt; [ 89 163 105]] </code></pre> <p>Just change the data-type of one array to something more suitable in your dot product and you're good to go : </p> <pre><code>r1 = subWin.T.dot(subWin.astype(np.uint32)) </code></pre>
3
2016-08-27T12:17:14Z
[ "python", "arrays", "numpy" ]
python: mutually exclusive positional arguments
39,180,785
<p>I want my program to accept mutually exclusive positional arguments, <em>and</em> the usage to be displayed as a group of arguments.<br> Currently I could only achieve one or the other, but not both... </p> <p>This is what I currently have: </p> <pre><code>def parse_arguments(): arg_parser = argparse.ArgumentParser(description = 'Project Builder') query_parser = arg_parser.add_argument_group('query', "Query current state") build_parser = arg_parser.add_argument_group('build', "Build project") # query arguments query_parser.add_argument('-s', '--servers', action = 'store_true', required = False, help = 'Display available servers') query_parser.add_argument('-u', '--users', action = 'store_true', required = False, help = 'Display current users') # build arguments build_parser.add_argument('-f', '--force', action = 'store', required = False, metavar = 'SERVER_NAME', help = 'Force build on SERVER_NAME') build_parser.add_argument('-c', '--clean', action = 'store_true', required = False, help = 'Clean repo before build') build_parser.add_argument('-v', '--verbosity', action = 'store_true', required = False, help = 'Print stderr to console') build_parser.add_argument('-p', '--project', action = 'store', required = True, metavar = 'project_A|project_B|project_C', type = project_name, help = 'Project to build (required)') return vars(arg_parser.parse_args()) args = parse_arguments() </code></pre> <p>Which gives the following: </p> <pre><code>usage: test.py [-h] [-s] [-u] [-f SERVER_NAME] [-c] [-v] -p project_A|project_B|project_C Project Builder optional arguments: -h, --help show this help message and exit query: Query current state -s, --servers Display available servers -u, --users Display current users build: Build project -f SERVER_NAME, --force SERVER_NAME Force build on SERVER_NAME -c, --clean Clean repo before build -v, --verbosity Print stderr to console -p project_A|project_B|project_C, --project project_A|project_B|project_C Project to build (required) </code></pre> <p>But what I really want is for <code>query</code> and <code>build</code> to be two mutually exclusive positional arguments. </p> <p>I tried using subparsers as follows:</p> <pre><code>def parse_arguments(): arg_parser = argparse.ArgumentParser(description = 'Project Builder') command_parser = arg_parser.add_subparsers(help = "Command") query_parser = command_parser.add_parser('query', help = "Query current state") build_parser = command_parser.add_parser('build', help = "Build project") # query arguments query_parser.add_argument('-s', '--servers', action = 'store_true', required = False, help = 'Display available servers') query_parser.add_argument('-u', '--users', action = 'store_true', required = False, help = 'Display current users') # build arguments build_parser.add_argument('-f', '--force', action = 'store', required = False, metavar = 'SERVER_NAME', help = 'Force build on SERVER_NAME') build_parser.add_argument('-c', '--clean', action = 'store_true', required = False, help = 'Clean repo before build') build_parser.add_argument('-v', '--verbosity', action = 'store_true', required = False, help = 'Print stderr to console') build_parser.add_argument('-p', '--project', action = 'store', required = True, metavar = 'project_A|project_B|project_C', type = project_name, help = 'Project to build (required)') return vars(arg_parser.parse_args()) </code></pre> <p>But this produces the following:</p> <pre><code>usage: test.py [-h] {query,build} ... Project Builder positional arguments: {query,build} Command query Query current state build Build project optional arguments: -h, --help show this help message and exit </code></pre> <p>Where what I want is a combination of the two attempts above, namely:</p> <pre><code>usage: test.py [-h] {query,build} ... Project Builder optional arguments: -h, --help show this help message and exit query: Query current state -s, --servers Display available servers -u, --users Display current users build: Build project -f SERVER_NAME, --force SERVER_NAME Force build on SERVER_NAME -c, --clean Clean repo before build -v, --verbosity Print stderr to console -p project_A|project_B|project_C, --project project_A|project_B|project_C Project to build (required) </code></pre> <p>Where <code>query</code> and <code>build</code> are mutually exclusive.<br> I know about the <code>ArgumentParser.add_mutually_exclusive_group(required=False)</code> method, but using it didn't help achieving what I wanted, since 1) the arguments must be optional when using it, and 2) the <code>usage</code> format is not like I want.</p>
3
2016-08-27T11:46:24Z
39,183,029
<p>In the first scenario, you could give <code>-p</code> choices</p> <pre><code>build_parser.add_argument('-p', '--project', action = 'store', # default required = True, choices = ['project_A','project_B','project_C'], # type = project_name, # doesn't make sense help = 'Project to build (required)') </code></pre> <p>or as a positional</p> <pre><code>build_parser.add_argument('project', choices = ['project_A','project_B','project_C'], help = 'Project to build') </code></pre> <p><code>type</code> must be a function, one that converts as string to something you want, eg <code>int('1')</code>, <code>float('12.343')</code>.</p> <p>The use of subparsers is similar. To the main parser the subparser argument is just a positional with choices. But the action taken is to deligate the parsing of the rest of the arguments to the subparser.</p> <p>Two mutually exclusive positionals doesn't make logical sense</p> <pre><code> `[foo | bar]` </code></pre> <p>It can't tell, based just on position, whether you want to assign the string to <code>foo</code> or to <code>bar</code>. But you are interested in assigning values based on value, or rather restricting values to a set of choices.</p> <p>Without looking at it carefully your subparsers code looks right, and should parse the input as you want. Have you tested it?</p> <p>The help display for subparsers is not as flexible as it could be, but reworking it takes a fair amount of work (there are SO questions about this). The current setup is to have separate help displays for the main parser and for each of the subparsers. There's no builtin comprehensive help display.</p>
0
2016-08-27T15:58:01Z
[ "python", "argparse" ]
What's the use of "flag" in pandas
39,180,793
<p>When i was training with an exercise for predictive modeling, I couldn't understand the use of flags. I googled it but I couldn't find the best explanation.</p> <pre><code>train = pd.read_csv('C:/Users/Analytics Vidhya/Desktop/challenge/Train.csv') test = pd.read_csv('C:/Users/Analytics Vidhya/Desktop/challenge/Test.csv') train['Type'] = 'Train' #Create a flag for Train and Test Data set test['Type'] = 'Test' fullData = pd.concat([train,test], axis=0) #Combined both Train and Test Data set </code></pre> <p>Can you explain what does flag means in Python <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> and what's the importance of flags. Thank you.</p>
1
2016-08-27T11:47:36Z
39,181,128
<p>I guess it's easier and faster to show it as an example:</p> <pre><code>In [102]: train = pd.DataFrame(np.random.randint(0, 5, (5, 3)), columns=list('abc')) In [103]: test = pd.DataFrame(np.random.randint(0, 5, (3, 3)), columns=list('abc')) In [104]: train Out[104]: a b c 0 3 4 0 1 0 0 1 2 2 4 1 3 4 2 0 4 2 4 0 In [105]: test Out[105]: a b c 0 1 0 3 1 3 3 0 2 4 4 3 </code></pre> <p>let's add <code>Type</code> column to each DF: </p> <pre><code>In [106]: train['Type'] = 'Train' In [107]: test['Type'] = 'Test' </code></pre> <p>now let's join / merge (<strong>vertically</strong>) both DFs - the <code>Type</code> column will help to distinguish data from two different DFs:</p> <pre><code>In [108]: fullData = pd.concat([train,test], axis=0) In [109]: fullData Out[109]: a b c Type 0 3 4 0 Train 1 0 0 1 Train 2 2 4 1 Train 3 4 2 0 Train 4 2 4 0 Train 0 1 0 3 Test 1 3 3 0 Test 2 4 4 3 Test </code></pre>
2
2016-08-27T12:26:30Z
[ "python", "pandas", "flags" ]
Pandas dataframe: ValueError: num must be 1 <= num <= 0, not 1
39,180,873
<p>I am getting the following error while I am trying to plot a <code>pandas dataframe</code>:</p> <blockquote> <p>ValueError: num must be 1 &lt;= num &lt;= 0, not 1</p> </blockquote> <p>Code:</p> <pre><code>import matplotlib.pyplot as plt names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety'] custom = pd.DataFrame(x_train) //only a portion of the csv custom.columns = names custom.hist() plt.show() </code></pre> <p>I have tried to read the file again from the <code>csv</code> and I am getting the exact same error.</p> <p>Edit:</p> <p><code>print x_train</code> output:</p> <blockquote> <p>[[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>[1.0 1.0 0.0 0.0 0.0 0.0]</p> <p>[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>..., </p> <p>[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>[0.3333333333333333 0.3333333333333333 2.0 2.0 2.0 2.0]</p> <p>[0.0 0.0 3.0 3.0 3.0 3.0]]</p> </blockquote> <p>Edit2:</p> <p>Complete list of errors(Traceback): </p> <blockquote> <p>Traceback (most recent call last):</p> <p>File "temp.py", line 104, in custom.dropna().hist()</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", line 2893, in hist_frame layout=layout)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", line 3380, in _subplots ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/figure.py", line 1005, in add_subplot a = subplot_class_factory(projection_class)(self, *args, **kwargs)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_subplots.py", line 64, in <strong>init</strong> maxn=rows*cols, num=num))</p> </blockquote>
1
2016-08-27T11:56:01Z
39,181,446
<p>So I'm pretty sure your issue is something to do with the format of the array train_x. I tried your program with an array of 10,000 rows and 6 cols and it worked fine so the issue is not size. For some reason, one of <code>len(x_train)</code> or <code>len(x_train[0])</code> is 0. What makes me think this is thus:</p> <p>The ValueError you are getting is from the matplotlib.axes._subplot module which deals with drawing many small subplots within a big plot (so each small histogram). The code of the module is this:</p> <pre><code>""" *rows*, *cols*, *num* are arguments where the array of subplots in the figure has dimensions *rows*, *cols*, and where *num* is the number of the subplot being created. *num* starts at 1 in the upper left corner and increases to the right. """ rows, cols, num = args rows = int(rows) cols = int(cols) if isinstance(num, tuple) and len(num) == 2: num = [int(n) for n in num] self._subplotspec = GridSpec(rows, cols)[num[0] - 1:num[1]] else: if num &lt; 1 or num &gt; rows*cols: raise ValueError( "num must be 1 &lt;= num &lt;= {maxn}, not {num}".format( maxn=rows*cols, num=num)) </code></pre> <p>Your issue is in this part (see explanation in comments in code): </p> <pre><code> if num &lt; 1 or num &gt; rows*cols: # maxN is the number of rows*cols and since this is showing 0 for you (in your error stacktrace), # it means the number of cols being passed into your histogram is 0. Don't know why though :P raise ValueError( "num must be 1 &lt;= num &lt;= {maxn}, not {num}".format( maxn=rows*cols, num=num)) </code></pre> <p>I don't know how you are reading your input format, but I'm pretty sure the problem is related to it. If you set x_train to this it works fine:</p> <pre><code> x_train = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.3333333333333333, 0.3333333333333333, 2.0, 2.0, 2.0, 2.0], [0.0, 0.0, 3.0, 3.0, 3.0, 3.0]] </code></pre> <p>Try doing this before calling the code in your question and see if that works:</p> <pre><code>x_train = list([list(x) for x in x_train]) </code></pre>
1
2016-08-27T13:01:30Z
[ "python", "pandas", "histogram" ]
Python threading sync
39,180,883
<p>I have a base class that has an empty method called <code>Update</code>. This <code>Update</code> method is inherited by X amount of different subclasses The base class calls the <code>Update</code> method once every 30 ticks (right now it's not. It's just doing it in a loop right now, but I plan to make it get called every 30 ticks soon.) Each subclass has its own method <code>Update</code> with its own set of instructions. It's working fine. However there is one problem and that is all the threads are clashing together. When they print out a message in the python shell they are blended together.</p> <p>I have done some research in to it but from what I have found it is confusing the heck out of me. All i want to do is have the output of obj1, obj2 and obj3 own there own lines and not smashed together.</p> <p>here is my current code</p> <pre><code>import _thread class BaseClass(object): def __init__(self, name): self.name = name _thread.start_new_thread( self.UpdateHandler,() ) def ClassType(self): """Returns a string of the childs type""" pass def UpdateHandler(self): #this part handles when to call the update. #it is allso needed so that it can be run in a thread. while True: self.Update() def Update(self): #This is a place holder. #It stops classes that dont have a Update function crashing when called pass #--------------------------------------------------------------------------------- class ChildClassA(BaseClass): def __init__(self, name): super(ChildClassA, self).__init__(name) def ClassType(self): return 'ChildClassA' def Update(self): print(self.name, ": is doing stuff CLASS A") #---------------------------------------------------------------------------------- class ChildClassB(BaseClass): def __init__(self, name): super(ChildClassB, self).__init__(name) def Update(self): print(self.name, "This is a completley diffeent action CLASS B") self.Hi() def ClassType(self): return 'ChildClassB' def Hi(self): print("Hi") #---------------------------------------------------------------------------------- class ChildClassC(BaseClass): def __init__(self, name): super(ChildClassC, self).__init__(name) def Update(self): print(self.name, "This is a completley diffeent action") #-------------------------------------------------------------------------------- obj1 = ChildClassA('Obj1') obj2 = ChildClassA('Obj2') obj3 = ChildClassB('Obj3') </code></pre>
0
2016-08-27T11:57:38Z
39,181,041
<p>What you need is a <code>semaphore</code>, which is a multi-threaded lock object. <a href="https://en.wikipedia.org/wiki/Semaphore_(programming)" rel="nofollow">https://en.wikipedia.org/wiki/Semaphore_(programming)</a>.</p> <p>You sometimes see the same principle in kindergarten or pre-schools where to go to the toilet you need to take a necklace or another object to indicate the toilet is not occupied.</p> <p>A semaphore object has two operations traditionally called <code>P</code> and <code>V</code>. The <code>P</code> operation requests the lock. If the lock is currently taken, the thread will wait until the lock becomes free. The <code>V</code> operation will free the lock, allowing another thread a chance to take the lock. <code>P</code> and <code>V</code> are abbreviations for the Dutch words "plaatsen" en "vrijgeven" ("put" and "release").</p> <p>In python you can create a semaphore object by using the <code>threading.Semaphore()</code> or the <code>_thread.request_lock()</code> factory functions. The resulting objects have two methods: <code>acquire</code> (=<code>P</code>) and <code>release</code> (=<code>V</code>). </p> <pre><code>import _thread class BaseClass(object): lock = _thread.request_lock() def __init__(self, name): self.name = name _thread.start_new_thread( self.UpdateHandler,() ) def ClassType(self): """Returns a string of the childs type""" pass def UpdateHandler(self): #this part handles when to call the update. #it is allso needed so that it can be run in a thread. while True: self.lock.acquire() self.Update() self.lock.release() def Update(self): #This is a place holder. #It stops classes that dont have a Update function crashing when called pass </code></pre>
1
2016-08-27T12:16:25Z
[ "python", "multithreading", "class" ]
ValueError: need more than 2 values to unpack
39,181,014
<p>I am doing this operation:</p> <pre><code>for model, dict in fullCostDict.items(): if dict['cost_matrix']: for i, (costDict, normalCostDict, normalCostDict1, normalCostDict2,normalCostDict3,normalCostDict4) in enumerate( zip(dict['cost_matrix'], dict['normalised_matrix'],dict['normalised_matrix_sum'],dict['normalised_matrix_sumSquared'],dict['normalised_matrix_sumExp'],dict['normalised_matrix_sigmoid'])): for count, (lb, cost),(lb1, cost1),(lb2, cost2),(lb3, cost3),(lb4, cost4),(lb5, cost5) in enumerate(zip(costDict.items(),normalCostDict.items(),normalCostDict1.items(),normalCostDict2.items(),normalCostDict3.items(),normalCostDict4.items())): </code></pre> <p>On this array:</p> <pre><code>fullCostDict = { 'open_cost_2': { 'normalised_matrix': [ { 'a': 0.0, 'c': 0.9318755256518082, 'b': 1.0 }, { 'a': 0.1, 'c': 0.0, 'b': 1.0 }, { 'a': 0.016098839385997755, 'c': 0.0, 'b': 1.0 } ], 'normalised_matrix_sum': [ { 'a': 0.046136534133533386, 'c': 0.4617404351087772, 'b': 0.49212303075768943 }, { 'a': 0.2637620662666319, 'c': 0.23767284111661885, 'b': 0.4985650926167493 }, { 'a': 0.06399035455925695, 'c': 0.050549254264535146, 'b': 0.8854603911762079 } ], 'normalised_matrix_sumExp': [ { 'a': 4.695521542065545e-52, 'c': 4.699339039254216e-51, 'b': 5.0085563115365814e-51 }, { 'a': 3.37e-08, 'c': 3.036666666666667e-08, 'b': 6.37e-08 }, { 'a': 4.7766666666666664e-08, 'c': 3.7733333333333334e-08, 'b': 6.609666666666667e-07 } ], 'cost_matrix': [ { 'a': 123, 'c': 1231, 'b': 1312 }, { 'a': 1011, 'c': 911, 'b': 1911 }, { 'a': 1433, 'c': 1132, 'b': 19829 } ], 'normalised_matrix_sumSquared': [ { 'a': 3.782480901546635e-05, 'c': 0.00037855560892714697, 'b': 0.0004034646294983077 }, { 'a': 0.00018368582782987458, 'c': 0.0001655171010415586, 'b': 0.0003472043689247184 }, { 'a': 3.613903429449092e-06, 'c': 2.854807175252179e-06, 'b': 5.000704194176277e-05 } ], 'normalised_matrix_sigmoid': [ { 'a': 1.0, 'c': 1.0, 'b': 1.0 }, { 'a': 1.0, 'c': 1.0, 'b': 1.0 }, { 'a': 1.0, 'c': 1.0, 'b': 1.0 } ] }, 'open_cost_1': { 'normalised_matrix': [ { 'a': 0.0, 'c': 1.0, 'b': 0.5925925925925926 }, { 'a': 0.0, 'c': 1.0, 'b': 0.05562060889929742 }, { 'a': 0.0, 'c': 1.0, 'b': 0.0009238586496266071 } ], 'normalised_matrix_sum': [ { 'a': 0.1518987341772152, 'c': 0.4936708860759494, 'b': 0.35443037974683544 }, { 'a': 0.0016556291390728477, 'c': 0.9442604856512141, 'b': 0.05408388520971302 }, { 'a': 9.306716534258754e-06, 'c': 0.9990584064147736, 'b': 0.0009322868686921517 } ], 'normalised_matrix_sumExp': [ { 'a': 3.200675556312609e-33, 'c': 1.0402195558015979e-32, 'b': 7.468242964729421e-33 }, { 'a': 8.246355023730644e-43, 'c': 4.703171148534378e-40, 'b': 2.6938093077520104e-41 }, { 'a': 3.413131807036764e-51, 'c': 3.66393239921894e-46, 'b': 3.4190554242225303e-49 } ], 'cost_matrix': [ { 'a': 24, 'c': 78, 'b': 56 }, { 'a': 3, 'c': 1711, 'b': 98 }, { 'a': 121, 'c': 12989121, 'b': 12121 } ], 'normalised_matrix_sumSquared': [ { 'a': 0.002449979583503471, 'c': 0.007962433646386281, 'b': 0.0057166190281747655 }, { 'a': 1.021403858319028e-06, 'c': 0.000582540667194619, 'b': 3.336585937175491e-05 }, { 'a': 7.171755367615439e-13, 'c': 7.698743657219539e-08, 'b': 7.18420221577411e-11 } ], 'normalised_matrix_sigmoid': [ { 'a': 0.99999999996224864, 'c': 1.0, 'b': 1.0 }, { 'a': 0.95257412682243336, 'c': 1.0, 'b': 1.0 }, { 'a': 1.0, 'c': 1.0, 'b': 1.0 } ] }, 'open_cost_threshold': { 'normalised_matrix': [ { 'a': 0.0, 'b': 1.0 }, { 'a': 0.1, 'b': 1.0 }, { 'a': 0.016098839385997755, 'b': 1.0 } ], 'normalised_matrix_sum': [ { 'a': 0.046136534133533386, 'b': 0.49212303075768943 }, { 'a': 0.2637620662666319, 'b': 0.4985650926167493 }, { 'a': 0.06399035455925695, 'b': 0.8854603911762079 } ], 'normalised_matrix_sumExp': [ { 'a': 4.695521542065545e-52, 'b': 5.0085563115365814e-51 }, { 'a': 3.37e-08, 'b': 6.37e-08 }, { 'a': 4.7766666666666664e-08, 'b': 6.609666666666667e-07 } ], 'cost_matrix': [ { 'a': 123, 'b': 1312 }, { 'a': 1011, 'b': 1911 }, { 'a': 1433, 'b': 19829 } ], 'normalised_matrix_sumSquared': [ { 'a': 3.782480901546635e-05, 'b': 0.0004034646294983077 }, { 'a': 0.00018368582782987458, 'b': 0.0003472043689247184 }, { 'a': 3.613903429449092e-06, 'b': 5.000704194176277e-05 } ], 'normalised_matrix_sigmoid': [ { 'a': 1.0, 'b': 1.0 }, { 'a': 1.0, 'b': 1.0 }, { 'a': 1.0, 'b': 1.0 } ] }, 'open_cost_1': { 'normalised_matrix': [ { 'a': 0.0, 'b': 0.5925925925925926 }, { 'a': 0.0, 'b': 0.05562060889929742 }, { 'a': 0.0, 'b': 0.0009238586496266071 } ], 'normalised_matrix_sum': [ { 'a': 0.1518987341772152, 'b': 0.35443037974683544 }, { 'a': 0.0016556291390728477, 'b': 0.05408388520971302 }, { 'a': 9.306716534258754e-06, 'b': 0.0009322868686921517 } ], 'normalised_matrix_sumExp': [ { 'a': 3.200675556312609e-33, 'b': 7.468242964729421e-33 }, { 'a': 8.246355023730644e-43, 'b': 2.6938093077520104e-41 }, { 'a': 3.413131807036764e-51, 'b': 3.4190554242225303e-49 } ], 'cost_matrix': [ { 'a': 24, 'b': 56 }, { 'a': 3, 'b': 98 }, { 'a': 121, 'b': 12121 } ], 'normalised_matrix_sumSquared': [ { 'a': 0.002449979583503471, 'b': 0.0057166190281747655 }, { 'a': 1.021403858319028e-06, 'b': 3.336585937175491e-05 }, { 'a': 7.171755367615439e-13, 'b': 7.18420221577411e-11 } ], 'normalised_matrix_sigmoid': [ { 'a': 0.99999999996224864, 'b': 1.0 }, { 'a': 0.95257412682243336, 'b': 1.0 }, { 'a': 1.0, 'b': 1.0 } ] } </code></pre> <p>}</p> <p>As you can see, I am trying to get to the key,value pairs of each dictionary with the list of dictionaries of each different type of <code>cost_matrix</code> within the full dictionary. What am I doing wrong here? Note, some of the inner dictionaries have different lengths (some have <code>a</code> and <code>b</code>, so 2 items, some have <code>a</code>,<code>b</code> and <code>c</code>, so 3 items).</p>
0
2016-08-27T12:12:39Z
39,181,068
<p>You are missing a paranthesis in last <code>for</code> loop. Though you expect a <code>count</code> and a tuple of tuples, you are getting a bunch of tuple. So, the fix would be adding a pair of <code>()</code> over the tuples.</p> <pre><code> for count, ((lb, cost),(lb1, cost1),(lb2, cost2),(lb3, cost3),(lb4, cost4),(lb5, cost5)) in enumerate(....... ^ ^ </code></pre>
1
2016-08-27T12:18:46Z
[ "python", "loops", "dictionary", "zip", "enumerate" ]
Python print next line while printing from for loop
39,181,088
<p>I am performing a for loop on a list and would like to find a match and print the next line. However, when I try to use the next() method I keep getting a failure. Can I please get some help in extracting the next line after a specified match?</p> <p>string (for loop output):</p> <pre><code>item_0 0 item_1 0 item_3 727 item_4 325 </code></pre> <p>For Loop to find match and next line:</p> <pre><code>result = tree.xpath('//tr/td/font/text()') for line in result: if 'item_3' in line: print(line.next()) </code></pre> <p>Error:</p> <pre><code>AttributeError: '_ElementStringResult' object has no attribute 'next' </code></pre>
0
2016-08-27T12:21:44Z
39,181,121
<p><code>line</code> is a <code>lxml.etree._ElementStringResult</code> (a modified <code>str</code>) in your code. <code>lxml.etree._ElementStringResults</code> do not have a <code>next</code> method which is why you are getting an <code>AttributeError</code>. </p> <p>You can set a flag indicating that the next line should be printed as follows:</p> <pre><code>print_line = False for line in result: if print_line: print(line) print_line = False if 'item_3' in line: print_line = True </code></pre>
2
2016-08-27T12:25:18Z
[ "python", "match" ]
Python print next line while printing from for loop
39,181,088
<p>I am performing a for loop on a list and would like to find a match and print the next line. However, when I try to use the next() method I keep getting a failure. Can I please get some help in extracting the next line after a specified match?</p> <p>string (for loop output):</p> <pre><code>item_0 0 item_1 0 item_3 727 item_4 325 </code></pre> <p>For Loop to find match and next line:</p> <pre><code>result = tree.xpath('//tr/td/font/text()') for line in result: if 'item_3' in line: print(line.next()) </code></pre> <p>Error:</p> <pre><code>AttributeError: '_ElementStringResult' object has no attribute 'next' </code></pre>
0
2016-08-27T12:21:44Z
39,181,151
<p>Haven't tested this, but try:</p> <pre><code>result = tree.xpath('//tr/td/font/text()') iter_result = iter(result) for line in iter_result: if 'item_3' in line: print(next(iter_result)) </code></pre>
1
2016-08-27T12:29:41Z
[ "python", "match" ]
Changing variable on another module for functions
39,181,091
<p>I have made two py files, in which <strong>main.py</strong> contains:</p> <pre><code>import module module.Print("This should not appear.") module.Silence = False module.Print("This should appear.") </code></pre> <p>The module imported is <strong>module.py</strong> which contains:</p> <pre><code>Silence = True def Print(Input, Sil= Silence): if Sil == False: print(Input) </code></pre> <p>The expected result should be:</p> <blockquote> <p>This should appear</p> </blockquote> <p>The result:</p> <blockquote> <p></p> </blockquote>
0
2016-08-27T12:21:55Z
39,181,210
<p>The issue is that you've defined your <code>Print</code> function with a default argument of True (since <code>Silent == True</code> when this module is imported, and the function created). Changing the module variable, <code>Silent</code> to False later isn't going to affect this function definition in any way. It's already set in stone. </p> <p>You could achieve what it looks like you want to doing something like (in <code>module.py</code>):</p> <pre><code>Silence = [True] def Print(Input, Sil= Silence): if Sil[0] == False: print(Input) </code></pre> <p>...</p> <p>And then setting <code>module.Silence[0] = False</code> in <code>main.py</code>.</p> <p>[I'm assuming the goal here was to call the function <em>without</em> passing in an explicit <code>Sil</code> argument. You can certainly just pass in an explicit second argument and have the function perform exactly how you expect instead]</p>
1
2016-08-27T12:36:03Z
[ "python", "python-3.x", "variables", "import" ]
Changing variable on another module for functions
39,181,091
<p>I have made two py files, in which <strong>main.py</strong> contains:</p> <pre><code>import module module.Print("This should not appear.") module.Silence = False module.Print("This should appear.") </code></pre> <p>The module imported is <strong>module.py</strong> which contains:</p> <pre><code>Silence = True def Print(Input, Sil= Silence): if Sil == False: print(Input) </code></pre> <p>The expected result should be:</p> <blockquote> <p>This should appear</p> </blockquote> <p>The result:</p> <blockquote> <p></p> </blockquote>
0
2016-08-27T12:21:55Z
39,192,340
<p>I think you are looking for a function with a default setting that can be dynamically changed. This will use the global <code>Silence</code> only if the <code>sil</code> argument is omitted in <code>Print()</code> function call.</p> <pre><code>def Print(input, sil=None): if sil is None: sil = Silence if not sil: print(input) </code></pre>
0
2016-08-28T14:32:20Z
[ "python", "python-3.x", "variables", "import" ]
Do locally set Cython compiler directives affect one or all functions?
39,181,180
<p>I am working on speeding up some Python/Numpy code with Cython, and am a bit unclear on the effects of "locally" setting (as defined <a href="http://docs.cython.org/en/latest/src/reference//compilation.html" rel="nofollow">here</a> in the docs) compiler directives. In my case I'd like to use:</p> <pre><code>@cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) #turn off bounds-checking </code></pre> <p>I understand that I can globally define this in my <code>setup.py</code> file, but I'm developing for non-Cython users and would like the directives to be obvious from the <code>.pyx</code> file.</p> <p>If I am writing a <code>.pyx</code> file with several functions defined in it, need I only set these once, or will they only apply to the next function defined? The reason I ask is that the documentation often says things like "turn off <code>boundscheck</code> for this function," making me wonder whether it only applies to the next function defined.</p> <p>In other words, do I need to do this:</p> <pre><code>import numpy as np cimport numpy as np cimport cython ctypedef np.float64_t DTYPE_FLOAT_t @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc1(np.ndarray[DTYPE_FLOAT_t] a): do things here def myfunc2(np.ndarray[DTYPE_FLOAT_t] b): do things here </code></pre> <p>Or do I need to do this:</p> <pre><code>import numpy as np cimport numpy as np cimport cython ctypedef np.float64_t DTYPE_FLOAT_t @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc1(np.ndarray[DTYPE_FLOAT_t] a): do things here @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc2(np.ndarray[DTYPE_FLOAT_t] b): do things here </code></pre> <p>Thanks!</p>
2
2016-08-27T12:32:44Z
39,181,291
<p>The manual does not say explicitly, but these directives are using <a href="https://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorator notation</a>. In plain Python,</p> <pre><code>@decorator2 @decorator1 def fn(args): body </code></pre> <p>is syntactic sugar for</p> <pre><code>def fn(args): body fn = decorator2(decorator1(fn)) </code></pre> <p>So my <em>expectation</em> is that the directives work like that, which would mean that they apply only to the next function.</p> <p>The Cython manual also says that the compiler directives can be used in <code>with</code> statements. What it <em>doesn't</em> say, unfortunately, is whether those can appear at top level:</p> <pre><code>with cython.wraparound(False), cython.boundscheck(False): def myfunc1(np.ndarray[DTYPE_FLOAT_t] a): do things here def myfunc2(np.ndarray[DTYPE_FLOAT_t] b): do things here </code></pre> <p>might be what you're looking for, or then again it might be a syntax error or a no-op. You're going to have to try it and see.</p>
1
2016-08-27T12:43:41Z
[ "python", "numpy", "cython" ]
Do locally set Cython compiler directives affect one or all functions?
39,181,180
<p>I am working on speeding up some Python/Numpy code with Cython, and am a bit unclear on the effects of "locally" setting (as defined <a href="http://docs.cython.org/en/latest/src/reference//compilation.html" rel="nofollow">here</a> in the docs) compiler directives. In my case I'd like to use:</p> <pre><code>@cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) #turn off bounds-checking </code></pre> <p>I understand that I can globally define this in my <code>setup.py</code> file, but I'm developing for non-Cython users and would like the directives to be obvious from the <code>.pyx</code> file.</p> <p>If I am writing a <code>.pyx</code> file with several functions defined in it, need I only set these once, or will they only apply to the next function defined? The reason I ask is that the documentation often says things like "turn off <code>boundscheck</code> for this function," making me wonder whether it only applies to the next function defined.</p> <p>In other words, do I need to do this:</p> <pre><code>import numpy as np cimport numpy as np cimport cython ctypedef np.float64_t DTYPE_FLOAT_t @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc1(np.ndarray[DTYPE_FLOAT_t] a): do things here def myfunc2(np.ndarray[DTYPE_FLOAT_t] b): do things here </code></pre> <p>Or do I need to do this:</p> <pre><code>import numpy as np cimport numpy as np cimport cython ctypedef np.float64_t DTYPE_FLOAT_t @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc1(np.ndarray[DTYPE_FLOAT_t] a): do things here @cython.wraparound (False) #turn off negative indexing @cython.boundscheck(False) # turn off bounds-checking def myfunc2(np.ndarray[DTYPE_FLOAT_t] b): do things here </code></pre> <p>Thanks!</p>
2
2016-08-27T12:32:44Z
39,183,975
<p>The <a href="http://cython.readthedocs.io/en/latest/src/reference/compilation.html#globally" rel="nofollow">documentation</a> states that if you want to set a compiler directive globally, you need to do so with a comment at the top of the file. eg.</p> <pre><code>#!python #cython: language_level=3, boundscheck=False </code></pre>
2
2016-08-27T17:38:33Z
[ "python", "numpy", "cython" ]
Attempt to call an undefined function glutInit
39,181,192
<p>I need a glut window in python. I have the following exception using Python 3.5 and PyOpenGL.GLUT</p> <pre><code>Traceback (most recent call last): File "D:\...\Test.py", line 47, in &lt;module&gt; if __name__ == '__main__': main() File "D:\...\Test.py", line 9, in main glutInit(sys.argv) File "C:\...\OpenGL\GLUT\special.py", line 333, in glutInit _base_glutInit( ctypes.byref(count), holder ) File "C:\...\OpenGL\platform\baseplatform.py", line 407, in __call__ self.__name__, self.__name__, OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling </code></pre> <p>Platform: <strong>Windows</strong></p> <p>Why do i get this error?</p> <p>Here is my code:</p> <pre><code>from OpenGL.GLUT import * import sys glutInit(sys.argv) </code></pre>
0
2016-08-27T12:34:12Z
39,181,193
<p><strong>Problems:</strong></p> <ul> <li>There was no problem with <code>pip install</code> or <code>easy_install</code></li> <li>The <code>glut.dll</code> and <code>glut32.dll</code> were missing. (They are not part of the PyPI package) you have to install them separately or <a href="ftp://ftp.sgi.com/opengl/glut/glut3.html.old#windows" rel="nofollow">download</a> it like I did.</li> </ul> <p>Unzipped the <code>dll</code> files from the <code>glutdlls.zip</code> and placed them next to my python file.</p> <p><strong>Note:</strong> You can add the <code>dll</code> files to your <code>PATH</code> variable. Not necessary to keep them next to the <code>py</code> file.</p>
0
2016-08-27T12:34:12Z
[ "python", "python-3.x", "glut", "pyopengl" ]
Flask-Migrate having issue with enum class in models
39,181,294
<p>Using flask-migrate before I was able to create enums by using flask-sqlalchemy's db.Enum and entering the values in as strings like so.</p> <pre><code>reservation_status = db.Enum('pending', 'confirmed, name='reservation_status_enum') </code></pre> <p>I decided to start using enum classes like the following. According to the <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight=enum#sqlalchemy.types.Enum" rel="nofollow">sqlalchemy docs</a> works fine.</p> <pre><code>class Status(enum.Enum): pending = 'pending' confirmed = 'confirmed' rejected = 'rejected' abandoned = 'abandoned' reservation_status = db.Enum(Status, name='reservation_status_enum') class Reservation(db.Model): __tablename__ = 'reservations' id = db.Column(db.Integer, primary_key=True) status = db.Column(reservation_status, default=Status.pending) ... </code></pre> <p>When I try to use the migrate command I get an invalid syntax error in the generated code as follows. The error is exactly what was written to the file.</p> <pre><code> sa.Column('status', sa.Enum(&lt;enum 'Status'&gt;, name='reservation_status_enum'), nullable=True), ^ SyntaxError: invalid syntax </code></pre>
1
2016-08-27T12:43:53Z
39,181,900
<p>Thanks to user @dim, I was able to resolve the issue by upgrading just sqlalchemy to beta 1.1.0b3. As is most cases, it was user error(me).</p> <p>All i did was </p> <pre><code>pip uninstall sqlalchemy pip install sqlalchemy==1.1.0b3 </code></pre>
1
2016-08-27T13:52:52Z
[ "python", "flask", "enums", "sqlalchemy", "alembic" ]
Using `map` to write lines to files
39,181,323
<p>I have a list of lines:</p> <pre><code>lines = [a,b,c,d] </code></pre> <p>And a list of files (created via <code>open(path string,'w')</code>:</p> <pre><code>files = [e,f,g,h] </code></pre> <p>What I am trying to do is write each line to its respective file (line <code>a</code> should go with file <code>e</code> and a new line). Note, this is all part of a much larger loop to generate the lines and put them in this list of lines you see:</p> <p>This is my current method:</p> <pre><code>map(lambda (x,y): y.write(x) + "\n",zip(lines,files)) </code></pre> <p>But this is what I am getting:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' </code></pre> <p>What is a way of achieving what I need? Writing each line to each file separately is very cumbersome.</p>
0
2016-08-27T12:47:57Z
39,181,344
<p>Did you mean to do:</p> <pre><code>map(lambda (x,y): y.write(x + "\n"), zip(lines,files)) </code></pre> <p>But I'd rather do it as:</p> <pre><code>for l, f in zip(lines,files): f.write(l + "\n") </code></pre>
4
2016-08-27T12:50:15Z
[ "python", "python-2.7", "function", "dictionary", "lambda" ]
How do I change a value of a variable using an if else statement?
39,181,330
<p>I've been on it for days but nothing is helping. The value of smallest does not change no matter what i do. it does not happen with the value of largest although it uses almost the same line of code.</p> <pre><code>smallest = None largest = None while True: num = raw_input("Enter a number: ") if num == "done": break try: x = int(num) if x &lt; smallest: smallest = x elif x &gt; largest: largest = x except: print"Invalid input" continue print "Maximum is", largest print "Minimum is", smallest </code></pre>
0
2016-08-27T12:48:23Z
39,181,381
<p>The problem is that you are, in both cases, comparing numbers to <code>None</code> in the first iteration. In Python 2, every number will come out as "greater" when compared to <code>None</code>, thus the code works for finding the maximum, but fails for finding the minimum.</p> <p>BTW, in Python 3, the same would give you a <code>TypeError</code>.</p> <p>To fix it, you can change your comparison to something like this, taking the <code>None</code> case into account:</p> <pre><code>if smallest is None or x &lt; smallest: </code></pre>
4
2016-08-27T12:54:49Z
[ "python", "python-2.7", "python-3.x" ]
How do I change a value of a variable using an if else statement?
39,181,330
<p>I've been on it for days but nothing is helping. The value of smallest does not change no matter what i do. it does not happen with the value of largest although it uses almost the same line of code.</p> <pre><code>smallest = None largest = None while True: num = raw_input("Enter a number: ") if num == "done": break try: x = int(num) if x &lt; smallest: smallest = x elif x &gt; largest: largest = x except: print"Invalid input" continue print "Maximum is", largest print "Minimum is", smallest </code></pre>
0
2016-08-27T12:48:23Z
39,181,750
<p>First, (almost) never use a bare <code>except</code> statement. You will catch exceptions you can't or don't want to handle (like <code>SystemExit</code>). At the very least, use <code>except Exception</code>.</p> <p>Second, your <code>except</code> block implies you only want to handle the <code>ValueError</code> that <code>int(num)</code> might raise. Catch that, and nothing else.</p> <p>Third, the code that compares <code>x</code> to <code>smallest</code> and <code>largest</code> is independent of the <code>ValueError</code> handling, so move that out of the <code>try</code> block to after the <code>try/except</code> statement.</p> <pre><code>smallest = None largest = None num = "not done" # Initialize num to avoid an explicit break while num != "done": num = raw_input("Enter a number: ") try: x = int(num) except: print "Invalid input" continue if smallest is None: smallest = x if largest is None: largest = x if x &lt; smallest: smallest = x elif x &gt; largest: largest = x print "Maximum is", largest print "Minimum is", smallest </code></pre> <p>Note that you can't fold the <code>None</code> checks into the <code>if/elif</code> statement, because if the user only enters one number, you need to make sure that <em>both</em> <code>smallest</code> and <code>largest</code> are set to that number. <em>After</em> the first number is entered, there is no case where a single number will update both <code>smallest</code> and <code>largest</code>, so <code>if/elif</code> is valid.</p>
1
2016-08-27T13:37:10Z
[ "python", "python-2.7", "python-3.x" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> <p>3</p> <p>Correct!</p> <p>Word 2/5: Potato How many vowels does the word contain?</p> <p>1</p> <p>Correct!</p> <p>Word 3/5: Name How many vowels does the word contain</p> <p>5</p> <p>Incorrect! Correct answer 4 </p> <p>Word 4/5: YES How many letters does the word contain? 3 Correct!</p> <p>Word 5/5: Day</p> <p>What is letter 3 of the word?</p> <p>Y</p> <p>Correct!</p> <p>Game Over. Your Score is 4/5</p> </blockquote> <pre><code>print('WELCOME TO YOUR QUIZ') # Import the random module to allow us to select the word list and questions at random. import random quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] s = random.sample (quizWords, 5) # loop through the list using enumerate for index,w in enumerate(s): print("Word {}/{}:{}".format(index+1,len(s),w)) </code></pre> <p>I want to generate a random number between 1 and 4, and use it to choose which question is asked for each word. </p> <p>If the random number is 1, I want to ask the user “How many letters does the word contain?” and prompt them for input. Assess their answer, and then print an appropriate message. How would i fit that in?</p>
1
2016-08-27T13:14:22Z
39,181,637
<p>I'm proposing a way to select a question, and associate a test function, which allows to define as many questions you want easily:</p> <pre><code>print('WELCOME TO YOUR QUIZ') # Import the random module to allow us to select the word list and questions at random. import random quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] s = random.sample (quizWords, 5) def test_nb_vows(word): return sum(word.upper().count(x) for x in "AEIOUY") qt = {"How many vowels does the word contain?" : test_nb_vows, "How many letters does the word contain?" : len} # loop through the list using enumerate for index,w in enumerate(s): print("Word {}/{}:{}".format(index+1,len(s),w)) # check question qk = random.choice(list(qt.keys())) answer = int(input(qk)) real_answer = qt[qk](w) if real_answer == answer: print("Correct!") else: print("Noooo it is {}".format(real_answer)) </code></pre> <p>The idea is to choose the question at random using <code>random.choice</code>. The choice is a key to a dictionary, and the value is the test function, which must have 1 parameters: the word itself, and returns the correct answer (restricted to a number right now), which is tested against user input</p> <p>That way you can define a lot of questions as long as you provide the relevant test function. You just have to enrich <code>qt</code> and code the test function (or use existing functions like I did by reusing <code>len</code>). Good luck.</p>
0
2016-08-27T13:25:01Z
[ "python", "python-3.x", "for-loop" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> <p>3</p> <p>Correct!</p> <p>Word 2/5: Potato How many vowels does the word contain?</p> <p>1</p> <p>Correct!</p> <p>Word 3/5: Name How many vowels does the word contain</p> <p>5</p> <p>Incorrect! Correct answer 4 </p> <p>Word 4/5: YES How many letters does the word contain? 3 Correct!</p> <p>Word 5/5: Day</p> <p>What is letter 3 of the word?</p> <p>Y</p> <p>Correct!</p> <p>Game Over. Your Score is 4/5</p> </blockquote> <pre><code>print('WELCOME TO YOUR QUIZ') # Import the random module to allow us to select the word list and questions at random. import random quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] s = random.sample (quizWords, 5) # loop through the list using enumerate for index,w in enumerate(s): print("Word {}/{}:{}".format(index+1,len(s),w)) </code></pre> <p>I want to generate a random number between 1 and 4, and use it to choose which question is asked for each word. </p> <p>If the random number is 1, I want to ask the user “How many letters does the word contain?” and prompt them for input. Assess their answer, and then print an appropriate message. How would i fit that in?</p>
1
2016-08-27T13:14:22Z
39,181,680
<p>Here's a possible solution:</p> <pre><code># Import the random module to allow us to select the word list and # questions at random. import random quizWords = [ 'WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY' ] s = random.sample(quizWords, 5) def f0(word): """ TODO """ return True def f1(word): """ TODO """ return True def f2(word): """ TODO """ return True def f3(word): """ TODO """ return True def f4(word): """ TODO """ return True questions = { 0: { "title": "How many consanants does the word {0} contain?", "f": f0 }, 1: { "title": "How many vowels does the word {0} contain?", "f": f1 }, 2: { "title": "How many vowels does the word {0} contain", "f": f2 }, 3: { "title": "How many letters does the word {0} contain?", "f": f3 }, 4: { "title": "What is letter 3 of the word {0}?", "f": f4 } } # loop through the list using enumerate for index, w in enumerate(s): print("Word {}/{}:{}".format(index + 1, len(s), w)) type_question = random.randint(0, 4) print("{}".format(questions[type_question]["title"].format(w))) questions[type_question]["f"](w) </code></pre> <p>As you can see, you just use random.randint to pick up a random question from the questions dictionary. Now you just need to complete the logic of function f0..f4 ;-) . Hope it helps!</p>
0
2016-08-27T13:29:34Z
[ "python", "python-3.x", "for-loop" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> <p>3</p> <p>Correct!</p> <p>Word 2/5: Potato How many vowels does the word contain?</p> <p>1</p> <p>Correct!</p> <p>Word 3/5: Name How many vowels does the word contain</p> <p>5</p> <p>Incorrect! Correct answer 4 </p> <p>Word 4/5: YES How many letters does the word contain? 3 Correct!</p> <p>Word 5/5: Day</p> <p>What is letter 3 of the word?</p> <p>Y</p> <p>Correct!</p> <p>Game Over. Your Score is 4/5</p> </blockquote> <pre><code>print('WELCOME TO YOUR QUIZ') # Import the random module to allow us to select the word list and questions at random. import random quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] s = random.sample (quizWords, 5) # loop through the list using enumerate for index,w in enumerate(s): print("Word {}/{}:{}".format(index+1,len(s),w)) </code></pre> <p>I want to generate a random number between 1 and 4, and use it to choose which question is asked for each word. </p> <p>If the random number is 1, I want to ask the user “How many letters does the word contain?” and prompt them for input. Assess their answer, and then print an appropriate message. How would i fit that in?</p>
1
2016-08-27T13:14:22Z
39,182,052
<p>This is how I would go about creating a quiz. Obviously you can update the print statements to follow your own desired format. Hope that this helps!</p> <pre><code>import random import string def consonant_count(word): word = word.lower() return len([x for x in word if x in consonants]) def vowel_count(word): word = word.lower() return len([x for x in word if x in vowels]) def prompt_letter_count(word): correct = word_map[word]['letters'] ans = input('How many letters does "{}" contain?'.format(word)) return check(ans, correct) def prompt_vowel_count(word): correct = word_map[word]['vowels'] ans = input('How many vowels does "{}" contain?'.format(word)) return check(ans, correct) def prompt_consonant_count(word): correct = word_map[word]['consonants'] ans = input('How many consonants does "{}" contain?'.format(word)) return check(ans, correct) def prompt_random_letter(word): n = random.randint(0, len(word)) correct = word[n-1] ans = raw_input('What is letter {} of "{}"?'.format(n, word)) return check(ans.lower(), correct.lower()) def check(ans, correct): if ans == correct: return prompt_correct() return prompt_incorrect() def prompt_correct(): print('That is correct! :)') return 1 def prompt_incorrect(): print('That is incorrect :(') return 0 def next_question(word): q_type = input_map[random.randint(1, 4)] return q_type(word) vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [x for x in string.ascii_lowercase if x not in vowels] quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] word_map = {x:{'consonants':consonant_count(x), 'vowels':vowel_count(x), 'letters':len(x)} for x in quizWords} input_map = {1:prompt_letter_count, 2:prompt_vowel_count, 3:prompt_consonant_count, 4:prompt_random_letter} def start_quiz(number_questions): current_question = 0 correct_questions = 0 if number_questions &gt; len(quizWords): number_questions = len(quizWords) sample_questions = random.sample(quizWords, number_questions) print('WELCOME TO YOUR QUIZ') print '---------------------' for x in sample_questions: print 'Question {}/{}:'.format(current_question, number_questions) correct_questions += next_question(x) print '---------------------' current_question += 1 print 'Congragulations on completing your quiz!' print " Score {}/{}:".format(correct_questions, number_questions) try_again = raw_input('Would you like to try again? (y/n)').lower() if try_again == 'y' or try_again == 'yes': start_quiz(number_questions) start_quiz(4) </code></pre>
1
2016-08-27T14:09:42Z
[ "python", "python-3.x", "for-loop" ]
'python' is not recognized as an internal or external command, operable program or batch file.Even though path is added
39,181,560
<p>I am on Windows 10, 64. </p> <p>When I run python in cmd, I got the message: 'python' is not recognized as an internal or external command, operable program or batch file.</p> <p>Even though I have added C:\Python27 to the environment variables. Please help </p>
-2
2016-08-27T13:16:03Z
39,181,598
<p>:( Turns out. I just need to restart the PC. </p>
-1
2016-08-27T13:19:51Z
[ "python", "windows", "batch-file" ]
'python' is not recognized as an internal or external command, operable program or batch file.Even though path is added
39,181,560
<p>I am on Windows 10, 64. </p> <p>When I run python in cmd, I got the message: 'python' is not recognized as an internal or external command, operable program or batch file.</p> <p>Even though I have added C:\Python27 to the environment variables. Please help </p>
-2
2016-08-27T13:16:03Z
39,181,625
<p>You can add the python folder to the <code>PATH</code> environment variable but I would suggest to install <a href="https://bitbucket.org/vinay.sajip/pylauncher" rel="nofollow">the launcher</a> (see <a href="https://www.python.org/dev/peps/pep-0397/" rel="nofollow">PEP 397</a>) instead (it is the same one that is installed by default with python 3.something) - and start python with just <code>py</code></p>
0
2016-08-27T13:23:39Z
[ "python", "windows", "batch-file" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </code></pre> <p>For this case, I would like to obtain all of the following types of sequences. For any given case, I would like to obtain all of the possible sequences of each type. Examples of desired sequences are given in parentheses below, for each case.</p> <ul> <li>1D lines <ul> <li>x axis (<code>0, 1, 2</code>)</li> <li>y axis (<code>0, 3, 6</code>)</li> <li>z axis (<code>0, 9, 18</code>)</li> </ul></li> <li>2D diagonals <ul> <li>x/y axes (<code>0, 4, 8</code>, <code>2, 4, 6</code>)</li> <li>x/z axes (<code>0, 10, 20</code>, <code>2, 10, 18</code>)</li> <li>y/z axes (<code>0, 12, 24</code>, <code>6, 12, 18</code>)</li> </ul></li> <li>3D diagonals <ul> <li>x/y/z axes (<code>0, 13, 26</code>, <code>2, 13, 24</code>)</li> </ul></li> </ul> <hr> <p>The solution should be generalized, so that it will generate all lines and diagonals for an array, regardless of the array's number of dimensions or length (which is constant across all dimensions).</p>
11
2016-08-27T13:20:07Z
39,183,487
<pre><code>In [1]: x=np.arange(27).reshape(3,3,3) </code></pre> <p>Selecting individual <code>rows</code> is easy:</p> <pre><code>In [2]: x[0,0,:] Out[2]: array([0, 1, 2]) In [3]: x[0,:,0] Out[3]: array([0, 3, 6]) In [4]: x[:,0,0] Out[4]: array([ 0, 9, 18]) </code></pre> <p>You could iterate over dimensions with an index list:</p> <pre><code>In [10]: idx=[slice(None),0,0] In [11]: x[idx] Out[11]: array([ 0, 9, 18]) In [12]: idx[2]+=1 In [13]: x[idx] Out[13]: array([ 1, 10, 19]) </code></pre> <p>Look at the code for <code>np.apply_along_axis</code> to see how it implements this sort of iteration. </p> <p>Reshape and split can also produce a list of <code>rows</code>. For some dimensions this might require a <code>transpose</code>:</p> <pre><code>In [20]: np.split(x.reshape(x.shape[0],-1),9,axis=1) Out[20]: [array([[ 0], [ 9], [18]]), array([[ 1], [10], [19]]), array([[ 2], [11], ... </code></pre> <p><code>np.diag</code> can get diagonals from 2d subarrays</p> <pre><code>In [21]: np.diag(x[0,:,:]) Out[21]: array([0, 4, 8]) In [22]: np.diag(x[1,:,:]) Out[22]: array([ 9, 13, 17]) In [23]: np.diag? In [24]: np.diag(x[1,:,:],1) Out[24]: array([10, 14]) In [25]: np.diag(x[1,:,:],-1) Out[25]: array([12, 16]) </code></pre> <p>And explore <code>np.diagonal</code> for direct application to the 3d. It's also easy to index the array directly, with <code>range</code> and <code>arange</code>, <code>x[0,range(3),range(3)]</code>.</p> <p>As far as I know there isn't a function to step through all these alternatives. Since dimensions of the returned arrays can differ, there's little point to producing such a function in compiled numpy code. So even if there was a function, it would step through the alternatives as I outlined.</p> <p>==============</p> <p>All the 1d lines</p> <pre><code>x.reshape(-1,3) x.transpose(0,2,1).reshape(-1,3) x.transpose(1,2,0).reshape(-1,3) </code></pre> <p>y/z diagonal and anti-diagonal</p> <pre><code>In [154]: i=np.arange(3) In [155]: j=np.arange(2,-1,-1) In [156]: np.concatenate((x[:,i,i],x[:,i,j]),axis=1) Out[156]: array([[ 0, 4, 8, 2, 4, 6], [ 9, 13, 17, 11, 13, 15], [18, 22, 26, 20, 22, 24]]) </code></pre>
3
2016-08-27T16:45:38Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </code></pre> <p>For this case, I would like to obtain all of the following types of sequences. For any given case, I would like to obtain all of the possible sequences of each type. Examples of desired sequences are given in parentheses below, for each case.</p> <ul> <li>1D lines <ul> <li>x axis (<code>0, 1, 2</code>)</li> <li>y axis (<code>0, 3, 6</code>)</li> <li>z axis (<code>0, 9, 18</code>)</li> </ul></li> <li>2D diagonals <ul> <li>x/y axes (<code>0, 4, 8</code>, <code>2, 4, 6</code>)</li> <li>x/z axes (<code>0, 10, 20</code>, <code>2, 10, 18</code>)</li> <li>y/z axes (<code>0, 12, 24</code>, <code>6, 12, 18</code>)</li> </ul></li> <li>3D diagonals <ul> <li>x/y/z axes (<code>0, 13, 26</code>, <code>2, 13, 24</code>)</li> </ul></li> </ul> <hr> <p>The solution should be generalized, so that it will generate all lines and diagonals for an array, regardless of the array's number of dimensions or length (which is constant across all dimensions).</p>
11
2016-08-27T13:20:07Z
39,185,702
<p><strong>This solution generalized over <code>n</code></strong></p> <p>Lets rephrase this problem as "find the list of indices".</p> <p>We're looking for all of the 2d index arrays of the form</p> <pre><code>array[i[0], i[1], i[2], ..., i[n-1]] </code></pre> <p>Let <code>n = arr.ndim</code></p> <p>Where <code>i</code> is an array of shape <code>(n, k)</code></p> <p>Each of <code>i[j]</code> can be one of:</p> <ul> <li>The same index repeated n times, <code>ri[j] = [j, ..., j]</code></li> <li>The forward sequence, <code>fi = [0, 1, ..., k-1]</code></li> <li>The backward sequence, <code>bi = [k-1, ..., 1, 0]</code></li> </ul> <p>With the requirements that each sequence is of the form <code>^(ri)*(fi)(fi|bi|ri)*$</code> (using regex to summarize it). This is because:</p> <ul> <li>there must be at least one <code>fi</code> so the "line" is not a point selected repeatedly</li> <li>no <code>bi</code>s come before <code>fi</code>s, to avoid getting reversed lines</li> </ul> <hr> <pre><code>def product_slices(n): for i in range(n): yield ( np.index_exp[np.newaxis] * i + np.index_exp[:] + np.index_exp[np.newaxis] * (n - i - 1) ) def get_lines(n, k): """ Returns: index (tuple): an object suitable for advanced indexing to get all possible lines mask (ndarray): a boolean mask to apply to the result of the above """ fi = np.arange(k) bi = fi[::-1] ri = fi[:,None].repeat(k, axis=1) all_i = np.concatenate((fi[None], bi[None], ri), axis=0) # inedx which look up every possible line, some of which are not valid index = tuple(all_i[s] for s in product_slices(n)) # We incrementally allow lines that start with some number of `ri`s, and an `fi` # [0] here means we chose fi for that index # [2:] here means we chose an ri for that index mask = np.zeros((all_i.shape[0],)*n, dtype=np.bool) sl = np.index_exp[0] for i in range(n): mask[sl] = True sl = np.index_exp[2:] + sl return index, mask </code></pre> <hr> <p>Applied to your example:</p> <pre><code># construct your example array n = 3 k = 3 data = np.arange(k**n).reshape((k,)*n) # apply my index_creating function index, mask = get_lines(n, k) # apply the index to your array lines = data[index][mask] print(lines) </code></pre> <pre><code>array([[ 0, 13, 26], [ 2, 13, 24], [ 0, 12, 24], [ 1, 13, 25], [ 2, 14, 26], [ 6, 13, 20], [ 8, 13, 18], [ 6, 12, 18], [ 7, 13, 19], [ 8, 14, 20], [ 0, 10, 20], [ 2, 10, 18], [ 0, 9, 18], [ 1, 10, 19], [ 2, 11, 20], [ 3, 13, 23], [ 5, 13, 21], [ 3, 12, 21], [ 4, 13, 22], [ 5, 14, 23], [ 6, 16, 26], [ 8, 16, 24], [ 6, 15, 24], [ 7, 16, 25], [ 8, 17, 26], [ 0, 4, 8], [ 2, 4, 6], [ 0, 3, 6], [ 1, 4, 7], [ 2, 5, 8], [ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 13, 17], [11, 13, 15], [ 9, 12, 15], [10, 13, 16], [11, 14, 17], [ 9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 22, 26], [20, 22, 24], [18, 21, 24], [19, 22, 25], [20, 23, 26], [18, 19, 20], [21, 22, 23], [24, 25, 26]]) </code></pre> <hr> <p>Another good set of test data is <code>np.moveaxis(np.indices((k,)*n), 0, -1)</code>, which gives an array where every value is its own index</p> <hr> <p>I've solved this problem before to implement a <a href="http://ericwieser.me/games/4d/">higher dimensional tic-tac-toe</a></p>
5
2016-08-27T20:59:01Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </code></pre> <p>For this case, I would like to obtain all of the following types of sequences. For any given case, I would like to obtain all of the possible sequences of each type. Examples of desired sequences are given in parentheses below, for each case.</p> <ul> <li>1D lines <ul> <li>x axis (<code>0, 1, 2</code>)</li> <li>y axis (<code>0, 3, 6</code>)</li> <li>z axis (<code>0, 9, 18</code>)</li> </ul></li> <li>2D diagonals <ul> <li>x/y axes (<code>0, 4, 8</code>, <code>2, 4, 6</code>)</li> <li>x/z axes (<code>0, 10, 20</code>, <code>2, 10, 18</code>)</li> <li>y/z axes (<code>0, 12, 24</code>, <code>6, 12, 18</code>)</li> </ul></li> <li>3D diagonals <ul> <li>x/y/z axes (<code>0, 13, 26</code>, <code>2, 13, 24</code>)</li> </ul></li> </ul> <hr> <p>The solution should be generalized, so that it will generate all lines and diagonals for an array, regardless of the array's number of dimensions or length (which is constant across all dimensions).</p>
11
2016-08-27T13:20:07Z
39,185,743
<p>np.einsum can be used to build all these kind of expressions; for instance:</p> <pre><code># 3d diagonals print(np.einsum('iii-&gt;i', a)) # 2d diagonals print(np.einsum('iij-&gt;ij', a)) print(np.einsum('iji-&gt;ij', a)) </code></pre>
2
2016-08-27T21:04:54Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
how to iterate over files in neighbouring dir
39,181,647
<p>I have a project structure like this</p> <pre><code>test/foo.py test/bar (directory with 10 files) src/ README.MD </code></pre> <p>From <code>foo.py</code> (which is in <code>test</code> dir), I wish to iterate over the 10 files in the <code>bar</code> dir (which is also in <code>test</code> dir). I tried to do this</p> <pre><code>import os for path in os.listdir('bar'): etc </code></pre> <p>But it says, "no such file or directory: bar"</p> <p>I then tried to do this</p> <pre><code>basepath = '/Users/me/pythonprojects/project_x/bar' for path in os.listdir(basepath): etc </code></pre> <p>However, when I counted over the number of files it iterated over, it was 0 (Not the expected 10).</p> <p>I then tried to do this</p> <pre><code> for path in '/Users/me/pythonprojects/project_x/test/bar': etc </code></pre> <p>However, it then iterated over every file in my system (hundreds, not just the 10 in bar).</p> <p>Although this is not what I wish to do, if from the command line I pass an argument of <code>.</code> to sys.argv[1] and then try to iterate over the bar dir like this</p> <pre><code>for path in sys.argv[1] </code></pre> <p>It iterates over the ten files in the bar dir.</p> <p>So, is there a way from <code>foo.py</code> to iterate over the files in <code>bar</code> (and only the files in <code>bar</code> dir)</p> <p>Update, when I do <code>print(os.getcwd(), "foo.py cwd")</code> in <code>foo.py</code> (and then call the test runner from <code>run_test.py</code> in root), it says</p> <pre><code>/Users/me/pythonprojects/project_x </code></pre> <p>i.e. <code>os.getcwd()</code> doesn't recognize that <code>foo.py</code> is in <code>test</code> dir of the project, which may be because the test is run from root?</p>
0
2016-08-27T13:25:55Z
39,181,765
<p>Use functions in <code>os.path</code> to do this (works only from a script, not REPL):</p> <pre><code>import os # retrieve path to directory with script script_dir = os.path.dirname(os.path.realpath(__file__)) bar_dir = os.path.join(script_dir, 'bar') for f in os.listdir(bar_dir): print(f) </code></pre>
1
2016-08-27T13:38:43Z
[ "python" ]
Sometimes request.session.session_key is None
39,181,655
<p>I hit a problem when get session_key from <code>request.session</code>.</p> <p>I am using Django1.8 and Python2.7.10 to set up a RESTful service.</p> <p>Here is snippet of my login view:</p> <pre><code>user = authenticate(username=userName, password=passWord) if user is not None: # the password verified for the user if user.is_active: # app_logger.debug("User is valid, active and authenticated") if hasattr(user, 'parent') : login(request, user) request.session['ut'] = 4 # user type 1 means admin, 2 for teacher, 3 for student, 4 for parents request.session['uid'] = user.id description = request.POST.get('description','') request.session['realname'] = user.parent.realname request.session['pid'] = user.parent.id devicemanage.update_user_device(devicetoken, user.id, ostype, description) children = parentmanage.get_children_info(user.parent.id) session_id = request.session.session_key user.parent.login_status = True user.parent.save() return JsonResponse({'retcode': 0,'notify_setting':{'receive_notify':user.parent.receive_notify,'notify_with_sound':user.parent.notify_with_sound,'notify_sound':user.parent.notify_sound,'notify_shake':user.parent.notify_shake},'pid':user.parent.id,'children':children,'name':user.parent.realname,'sessionid':session_id,'avatar':user.parent.avatar,'coins':user.parent.coins}) </code></pre> <p>Now when this function is called, I see sometimes <code>session_id</code> is <code>None</code> within the response.</p> <p>So, after debugging (I set breakpoint at the <code>return JsonResponse(...)</code> line), I see that when I hit the breakpoint the <code>request.session._session_key</code> is <code>None</code>, but <code>request.session.session_key</code> is <code>u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1'</code> and <code>session_id</code> is also <code>None</code>. </p> <p>Does anyone know how can this happen? Why isn't the value of <code>session_key</code> set when assigning it to <code>session_id</code> before returning the response?</p>
0
2016-08-27T13:27:04Z
39,188,274
<p>According to John's suggestion.</p> <p>I fixed the problem by this snippet:</p> <pre><code>if not request.session.session_key: request.session.save() session_id = request.session.session_key </code></pre>
0
2016-08-28T05:24:33Z
[ "python", "django", "session", "django-sessions" ]
Django : how to pass event.id/package.id in a template
39,181,669
<p>I have three jobs to be done 1) Read Packages related to an event 2) Update Packages related to that event one by one. 3) Or delete the same package related to that event. I have my views.py like this : </p> <pre><code>@login_required def update_package(request, pk ): package = Packages.objects.get(pk = pk) event = AddEvent.objects.get(EventId = package.PackageId) if request.method == 'POST': f1 = PackageForm(request.POST, instance = event) if f1.is_valid(): f1.save() return redirect('update_package' , package , event.id ) else: f1 = PackageForm(instance = event) return render(request,'addpackage.html', {'form':f1}) @login_required def delete_package(request, pk): PackageId = Packages.objects.get(pk=pk) if request.method == 'POST' : PackageId.delete() return redirect('read_package' , PackageId) return render(request, 'package_confirm_delete.html',{'object':PackageId}) </code></pre> <p>And I have my urls.py as</p> <pre><code>url(r'^update_package/(?P&lt;id&gt;.+)/(?P&lt;pk&gt;.+)$',update_package,name='update_package'), url(r'^delete_package/(?P&lt;id&gt;.+)/(?P&lt;pk&gt;.+)$', delete_package, name='delete_package'), </code></pre> <p>but it gives me an error like this </p> <pre><code>Reverse for 'update_package' with arguments '(34,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['organiser/update_package/(?P&lt;id&gt;.+)/(?P&lt;pk&gt;.+)$'] </code></pre> <p>I am new to all this and I am also not sure if I am doing it right. To read the package I want the url to be like this </p> <pre><code>localhost:8000/organiser/read_package/9 </code></pre> <p>And to update the package 34 in event 9 </p> <pre><code>localhost:8000/organiser/update_package/9/34 </code></pre> <p>Please suggest some way out. Any help is really appreciable And thanks in advance. </p> <p>in My home.html related to models.read_events</p> <pre><code>{% for event in object_list %} &lt;a href="{% url 'read_package' event.id %}" class="btn btn-primary"&gt;Read Packages&lt;/a&gt; {% endfor %} </code></pre> <p>in my Package_home.html related to models.update_package</p> <pre><code>{% for xyz in object_list %} &lt;a href="{% url 'update_package' xyz.id %}" class="btn btn-primary"&gt;Update&lt;/a&gt; &lt;a href="{% url 'delete_package' xyz.id %}" class="btn btn-primary"&gt;delete&lt;/a&gt; {% endfor %} </code></pre> <p>PS : Django version : 1.10</p>
0
2016-08-27T13:28:05Z
39,181,925
<p>You need to add an <code>id</code> argument to your <code>update_package</code> and <code>delete_package</code> views.</p> <pre><code>def update_package(request, id, pk): def delete_package(request, id, pk): </code></pre> <p>These arguments must match the ones you have on your urls.</p> <p>Your <code>delete_package</code> view has errors. You have to redirect to an actual URL, not just the name, you can <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse" rel="nofollow">use <code>reverse</code> for this</a>. And you can't redirect to a page of a deleted object.</p> <pre><code>from django.urls import reverse @login_required def delete_package(request, id, pk): event = Event.objects.get(id=id) package = Package.objects.get(pk=pk) if request.method == 'POST': package.delete() return redirect(reverse('read_package', args=[event.id])) return render(request, 'package_confirm_delete.html',{'object':PackageId}) </code></pre> <p>To use the url in the template use, here's a example:</p> <pre><code>&lt;a href="{% url read_package package.id %}"&gt;{{ package.name }}&lt;/a&gt; </code></pre>
0
2016-08-27T13:54:45Z
[ "python", "django", "django-templates", "django-views" ]
can I use Numpy genfromtxt to get names then skip a specifc row before continuing?
39,181,748
<p>I have a series of large CSV files contain sensor data samples.</p> <p>The format of each file is</p> <pre><code>Row 0 Column names Row 1 Column unit of measurement. Row 2 to EOF: time-stamp of sample was taken,voltage measurement from all sensors..... </code></pre> <p>I cannot modify the original file</p> <p>So i would like to use <code>numpy.gentromtxt(filename,Names=True,delimiter=',',dtype=None)</code></p> <p>So far to avoid corrupting the output i have skipped the header lines and manually added the column names later. This is not ideal as each file potentially a different order of sensors- and the information is there for the taking.</p> <p>Any help/Direction would be greatly appreciated.</p>
1
2016-08-27T13:37:01Z
39,183,110
<p>I can see several options:</p> <ul> <li><p>Open the file to read just the header line, parse the names yourself; run <code>genfromtxt</code> with the custom names and skip_header</p></li> <li><p>trick <code>genfromtxt</code> into treating the 2nd line as a comment line</p></li> <li><p>open the file yourself; pass lines through a filter to <code>genfromtxt</code>. The filter function would remove the second line. (<code>genfromtxt</code> works with a list of lines, or anything that feeds it lines).</p></li> - </ul>
0
2016-08-27T16:06:02Z
[ "python", "numpy" ]
Using Python libraries in Racket
39,181,788
<p>Can I use Python code and libraries in Racket? I have installed PyonR (<a href="https://github.com/pedropramos/PyonR" rel="nofollow">https://github.com/pedropramos/PyonR</a>) in DrRacket so I can choose "#lang python" and run Python code. But how can I combine Racket and Python language codes for my application?</p> <p>There is also a limited Python to Lisp translator at <a href="https://github.com/nurv/pnil" rel="nofollow">https://github.com/nurv/pnil</a> . Is there something similar for Racket?</p> <hr> <p>Edit: As advised in comments, I tried following. This python code in file "pysamples.rkt" works well in DrRacket: </p> <pre><code>#lang python def greet(name): print 'Hello', name greet('Alfred') </code></pre> <p>Output: </p> <pre><code>Hello Alfred </code></pre> <p>I tried using above definition in Racket code, but it did not work. Following is the Racket code: </p> <pre><code>#lang racket ; (require python/config) (enable-cpyimport!) ; ran this once; worked. (#%require "pysamples.rkt") (greet "Racket_code") </code></pre> <p>The error is: </p> <pre><code>greet: unbound identifier in module in: greet </code></pre>
2
2016-08-27T13:41:23Z
39,186,289
<p><a href="https://github.com/pedropramos/PyonR" rel="nofollow">Accoring to the readme</a> you can import python 2.7 packages, but you need to use <code>cpyimport</code>. One of the examples looks like this:</p> <pre><code>#lang python cpyimport numpy as np from "racket" import time def add_arrays(n): result = np.zeros((100,100)) for i in range(n): result += np.random.randint(0, 100000, (100,100)) return result print time(add_arrays(10000)) </code></pre> <p>Looking at the code, a pure python library you could just import give that it's in rackets paths and was given <code>#lang python</code> top line. all defined are always exported.</p>
3
2016-08-27T22:19:16Z
[ "python", "racket", "ffi" ]
Using Python libraries in Racket
39,181,788
<p>Can I use Python code and libraries in Racket? I have installed PyonR (<a href="https://github.com/pedropramos/PyonR" rel="nofollow">https://github.com/pedropramos/PyonR</a>) in DrRacket so I can choose "#lang python" and run Python code. But how can I combine Racket and Python language codes for my application?</p> <p>There is also a limited Python to Lisp translator at <a href="https://github.com/nurv/pnil" rel="nofollow">https://github.com/nurv/pnil</a> . Is there something similar for Racket?</p> <hr> <p>Edit: As advised in comments, I tried following. This python code in file "pysamples.rkt" works well in DrRacket: </p> <pre><code>#lang python def greet(name): print 'Hello', name greet('Alfred') </code></pre> <p>Output: </p> <pre><code>Hello Alfred </code></pre> <p>I tried using above definition in Racket code, but it did not work. Following is the Racket code: </p> <pre><code>#lang racket ; (require python/config) (enable-cpyimport!) ; ran this once; worked. (#%require "pysamples.rkt") (greet "Racket_code") </code></pre> <p>The error is: </p> <pre><code>greet: unbound identifier in module in: greet </code></pre>
2
2016-08-27T13:41:23Z
39,194,018
<p>The PyonR project is the closest ready-to-use way of using Python libraries from Racket that I know of. However note that there is a difference between Python libraries written in Python and Python libraries that are a thin Python layer on top of a C library. As you have experienced the latter type is not working (to my knowledge at least - but Pedro is the one to ask).</p> <p>If you need to use a library written in language X (for X could be Python) you can always write a "listener" program in language X that waits for messages from a Racket program, and when a message is received, computes an answer and sends it back to the Racket program. How to send and receive messages is up to you, but a simple option is to have two files, one "R-to-X" which Racket writes to and X reads from, and another "X-to-R" where Racket receives the messages.</p> <p>This approach has some overhead, but if the computation takes longer than sending the message, then it is a viable solution.</p>
2
2016-08-28T17:33:33Z
[ "python", "racket", "ffi" ]
Remove u' in json list
39,181,791
<p>I have a python script that queries servers that comes back with a set of information. Which i need to put into a database which is used by a php website. How ever there is a specific field that i get returned the <code>description</code> field which is user input and in some cases a few ASCII characters are used but before i can put this in the database i have to convert it to utf-8. It goes all right but it leaves me with a problem as it return a JSON array with <code>u'</code> characters which makes it unreadable </p> <p>I am doing the following to the input:</p> <pre><code>unicode(status.description).encode('utf8') </code></pre> <p>Which returns me the following string</p> <pre><code>{u'text': u'', u'extra': [{u'color': u'white', u'text': u' '}, {u'color': u'dark_gray', u'text': u'\xbb '}, {u'color': u'gold', u'text': u'Velocity', u'bold': True}, {u'color': u'red', u'text': u'MC ', u'bold': True}, {u'color': u'dark_gray', u'text': u'\xab\n'}, {u'color': u'white', u'text': u' '}, {u'color': u'gray', u'text': u'\u25b6 '}, {u'color': u'yellow', u'text': u'HCF SOTW ', u'bold': True}, {u'color': u'red', u'text': u'8/28 ', u'italic': True}, {u'color': u'gold', u'text': u'3PM EST ', u'italic': True}, {u'color': u'gray', u'text': u'\u25c0'}]} </code></pre> <p>While i need something like:</p> <pre><code>{"extra":[{"text":" ","color":"white"},{"text":"» ","color":"dark_gray"},{"text":"Velocity","color":"gold","bold":true},{"text":"MC ","color":"red","bold":true},{"text":"«\n","color":"dark_gray"},{"text":" ","color":"white"},{"text":"▶ ","color":"gray"},{"text":"2.0 ","color":"red","bold":true},{"text":"OPFACTIONS HAS BEEN RELEASED ","color":"yellow","bold":true},{"text":"◀","color":"gray"}],"text":""} </code></pre> <p>As someone not that experienced with python i have no idea how i could solve this i tried a few different ways of encoding it like hoping it would turn out different </p> <pre><code>status.description.encode('utf8') unicode(status.description).encode('utf8') status.description.encode('utf-8') unicode(status.description).encode('utf-8') </code></pre> <p>And a few with ASCII but so far no dice.</p> <p>Is there a way i can remove this <code>u</code> from the list before i put it in the database but still have it utf8 encoded? (Or via php if possible)</p>
0
2016-08-27T13:41:45Z
39,181,874
<p>If <code>status.description</code> is returning a dict and you want it to be JSON, you should call <code>json.dumps()</code> on it, not <code>unicode()</code>.</p> <p>However, the presence of <code>u</code> characters in a dict is <em>not</em> a problem and does not need to be fixed.</p>
2
2016-08-27T13:49:18Z
[ "php", "python", "database", "encoding", "user-input" ]
Remove u' in json list
39,181,791
<p>I have a python script that queries servers that comes back with a set of information. Which i need to put into a database which is used by a php website. How ever there is a specific field that i get returned the <code>description</code> field which is user input and in some cases a few ASCII characters are used but before i can put this in the database i have to convert it to utf-8. It goes all right but it leaves me with a problem as it return a JSON array with <code>u'</code> characters which makes it unreadable </p> <p>I am doing the following to the input:</p> <pre><code>unicode(status.description).encode('utf8') </code></pre> <p>Which returns me the following string</p> <pre><code>{u'text': u'', u'extra': [{u'color': u'white', u'text': u' '}, {u'color': u'dark_gray', u'text': u'\xbb '}, {u'color': u'gold', u'text': u'Velocity', u'bold': True}, {u'color': u'red', u'text': u'MC ', u'bold': True}, {u'color': u'dark_gray', u'text': u'\xab\n'}, {u'color': u'white', u'text': u' '}, {u'color': u'gray', u'text': u'\u25b6 '}, {u'color': u'yellow', u'text': u'HCF SOTW ', u'bold': True}, {u'color': u'red', u'text': u'8/28 ', u'italic': True}, {u'color': u'gold', u'text': u'3PM EST ', u'italic': True}, {u'color': u'gray', u'text': u'\u25c0'}]} </code></pre> <p>While i need something like:</p> <pre><code>{"extra":[{"text":" ","color":"white"},{"text":"» ","color":"dark_gray"},{"text":"Velocity","color":"gold","bold":true},{"text":"MC ","color":"red","bold":true},{"text":"«\n","color":"dark_gray"},{"text":" ","color":"white"},{"text":"▶ ","color":"gray"},{"text":"2.0 ","color":"red","bold":true},{"text":"OPFACTIONS HAS BEEN RELEASED ","color":"yellow","bold":true},{"text":"◀","color":"gray"}],"text":""} </code></pre> <p>As someone not that experienced with python i have no idea how i could solve this i tried a few different ways of encoding it like hoping it would turn out different </p> <pre><code>status.description.encode('utf8') unicode(status.description).encode('utf8') status.description.encode('utf-8') unicode(status.description).encode('utf-8') </code></pre> <p>And a few with ASCII but so far no dice.</p> <p>Is there a way i can remove this <code>u</code> from the list before i put it in the database but still have it utf8 encoded? (Or via php if possible)</p>
0
2016-08-27T13:41:45Z
39,181,899
<p><code>print(some_dict)</code> print string representation of a dict object. You need to convert dict object to a JSON.</p> <pre><code>import json print(json.dumps(some_dict)) </code></pre>
0
2016-08-27T13:52:51Z
[ "php", "python", "database", "encoding", "user-input" ]
Spark job aborted
39,181,884
<p>I would like to add a prediction column to my dataframe given the logistic regression model. The function is below:</p> <pre><code>def add_probability(df, model): coefficients_broadcast = sc.broadcast(model.coefficients) intercept = model.intercept def get_p(features): # Compute the raw value raw_prediction = coefficients_broadcast.value.dot(features) # Bound the raw value between 20 and -20 if raw_prediction&gt;20: raw_prediction=20 if raw_prediction&lt;-20: raw_prediction=-20 print raw_prediction # Return the probability return (1+exp(-raw_prediction))^(-1) get_p_udf = udf(get_p, DoubleType()) return df.withColumn('p', get_p_udf('features')) </code></pre> <p>In the nested function get_p, it calculates the probability for an observation given a list of features. So, after I define the function, I apply it to my training dataframe. </p> <pre><code>add_probability_model_basic = lambda df: add_probability(df, lr_model_basic) training_predictions = add_probability_model_basic(ohe_train_df).cache() print training_predictions.first() </code></pre> <p>However, when I tried to see the first row, the following error comes:</p> <p><code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 98.0 failed 1 times, most recent failure: Lost task 0.0 in stage 98.0 (TID 270, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last)</code></p> <p>And if I comment out the last print command, it seems that my code generates the <code>training_predictions</code> dataframe successfully.I am very frustrated why it cannot print out the first row?</p>
-1
2016-08-27T13:50:25Z
39,185,927
<p>You will absolutely love the reason why it fails:</p> <pre><code>return (1+exp(-raw_prediction))^(-1) </code></pre> <p>should be</p> <pre><code>return (1+exp(-raw_prediction))**(-1) </code></pre> <p>Glad I could help</p>
0
2016-08-27T21:31:45Z
[ "python", "apache-spark" ]
Keras Convolutional Autoencoder: Layer Shapes
39,181,976
<p>I've got a list of about 70,000 training images, each shaped (no. of colour channels, height width) = (3, 30, 30), and about 20,000 testing images. My convolutional autoencoder is defined as:</p> <pre><code> # Same as the code above, but with some params changed # Now let's define the model. # Set input dimensions: input_img = Input(shape=(3, 30, 30)) # Encoder: define a chain of Conv2D and MaxPooling2D layers x = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(input_img) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(x) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(x) encoded = MaxPooling2D((2, 2), border_mode='same')(x) # at this point, the representation is (8, 4, 4) i.e. 128-dimensional # Decoder: a stack of Conv2D and UpSampling2D layers x = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(encoded) x = UpSampling2D((2, 2))(x) x = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(x) x = UpSampling2D((2, 2))(x) x = Convolution2D(128, 3, 3, activation='relu')(x) x = UpSampling2D((2, 2))(x) decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x) autoencoder2 = Model(input_img, decoded) autoencoder2.compile(optimizer='adadelta', loss='mse') </code></pre> <p>Which is the autoencoder from <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow">here</a>. </p> <p>It throws an error:</p> <pre><code>Error when checking model target: expected convolution2d_14 to have shape (None, 1, 28, 28) but got array with shape (76960, 3, 30, 30) </code></pre> <p>which is weird because I've clearly changed the specified the input shape as (3, 30, 30). Is there some implementation technicality I'm missing?</p>
1
2016-08-27T14:00:52Z
39,551,007
<p>You forgot to add border_mode='same' in the last convnet layer of the decoder . </p>
0
2016-09-17T19:42:49Z
[ "python", "autoencoder" ]
Urwid colored Text simplified
39,182,074
<p>This is my broken code (technically works but doesn't change color)</p> <pre><code>import urwid txt = urwid.AttrMap(urwid.Text(u"Hello World"), 'dark blue') fill = urwid.Filler(txt, 'top') loop = urwid.MainLoop(fill) loop.run() </code></pre> <p>Honestly all I want to do is change the color of the text, it seems so simple of a task but with urwid, a little confusing.</p> <p>Here's how they did it in their example: <a href="https://github.com/urwid/urwid/blob/5c7bff3d381e855b483b7b65688ce2d4f53cdd1b/docs/manual/safe_combinations.py" rel="nofollow">https://github.com/urwid/urwid/blob/5c7bff3d381e855b483b7b65688ce2d4f53cdd1b/docs/manual/safe_combinations.py</a></p>
0
2016-08-27T14:11:33Z
39,182,318
<p>From the <a href="http://urwid.org/reference/widget.html#text" rel="nofollow">manual</a>, there is no argument for color:</p> <blockquote> <p>class urwid.Text(markup, align='left', wrap='space', layout=None)</p> </blockquote> <p>You have to define a pallet, example:</p> <pre><code>import urwid palette = [("text", "dark blue", 'white')] text = urwid.Text(("text", u'Hello World')) fill = urwid.Filler(text, 'top') urwid.MainLoop(fill, palette).run() </code></pre> <p><a href="http://i.stack.imgur.com/XQXd3.gif" rel="nofollow"><img src="http://i.stack.imgur.com/XQXd3.gif" alt="enter image description here"></a></p> <p>For Display attributes, visit: <a href="http://urwid.org/tutorial/index.html#display-attributes" rel="nofollow">http://urwid.org/tutorial/index.html#display-attributes</a></p> <p>You can follow some advanced examples at: <a href="http://urwid.org/examples/index.html" rel="nofollow">http://urwid.org/examples/index.html</a></p>
0
2016-08-27T14:39:51Z
[ "python", "python-2.7" ]
Subplots mess with my plot
39,182,249
<p>I have the following plot function that saves a random walk input <em>(the random walk is supposed to mimic a stock and bond portfolio that rebalances between each other given specific inputs, the exposure is supposed to show the exposure to the stock portfolio)</em>: </p> <pre><code>def stock_save_img_run(k): stock_vals = pd.read_csv('stock_vals_run_' + str(k) + '.csv', sep=';', encoding='utf-8-sig') plt.subplot(2, 1, 1) plt.plot(stock_vals['date'], stock_vals['stock_val'], color='#191970') plt.plot(stock_vals['date'], stock_vals['protected_amt'], color='#191970', ls='dashed') plt.stackplot(stock_vals['date'], stock_vals['exposure'] * stock_vals['stock_val'], (1 - stock_vals['exposure']) * stock_vals['stock_val'], color=('gray'), colors=('gray', 'silver')) plt.subplot(2, 1, 2) plt.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5') plt.ylabel('Exposure (in %)') plt.savefig('chart_' + str(k) + '.png') plt.show() plt.cla() del stock_vals </code></pre> <p>The regular output should look like this: <a href="http://i.stack.imgur.com/iujgx.png" rel="nofollow"><img src="http://i.stack.imgur.com/iujgx.png" alt="correct output"></a></p> <p>This works for the first run. If I run the script again, the output will look like this: <a href="http://i.stack.imgur.com/F6CNx.png" rel="nofollow"><img src="http://i.stack.imgur.com/F6CNx.png" alt="incorrect output"></a></p> <p>In order to get the plot to look normal again, I have to uncomment this line:<br> <code>##plt.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5')</code></p> <p>As you can imagine, the output will look like this for this particular run: <a href="http://i.stack.imgur.com/tp5OL.png" rel="nofollow"><img src="http://i.stack.imgur.com/tp5OL.png" alt="third run to reset"></a></p> <p>As you can see, the chart on the top looks normal again. When I run it again (fourth run), both charts will look like they are supposed to look. The fifth run will destroy everything again - rinse and repeat.</p> <p>Given that I know the workaround to get it solved, I'm flabbergasted as to why this occurs.</p>
0
2016-08-27T14:32:12Z
39,183,501
<p>Obtaining handles over separate <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">Axes</a> instances might be a step in a helpful direction:</p> <pre><code>def stock_save_img_run(k): stock_vals = pd.read_csv('stock_vals_run_' + str(k) + '.csv', sep=';', encoding='utf-8-sig') fig, (top_axes, bottom_axes) = plt.subplots(2, 1) top_axes.plot(stock_vals['date'], stock_vals['stock_val'], color='#191970') top_axes.plot(stock_vals['date'], stock_vals['protected_amt'], color='#191970', ls='dashed') top_axes.stackplot(stock_vals['date'], stock_vals['exposure'] * stock_vals['stock_val'], (1 - stock_vals['exposure']) * stock_vals['stock_val'], color=('gray'), colors=('gray', 'silver')) bottom_axes.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5') bottom_axes.set_ylabel('Exposure (in %)') plt.savefig('chart_' + str(k) + '.png') plt.show() top_axes.cla() bottom_axes.cla() del stock_vals </code></pre>
2
2016-08-27T16:47:55Z
[ "python", "matplotlib", "stacked-area-chart" ]
How to delay a python program in progress through another python code (in Raspberry Pi)
39,182,251
<p>I want to know how to delay and execute a python program in progress in Raspberry Pi through another python code. For example, I have a python file named example.py which contains GPIO commands and the python file is in progress. But I want the GPIO process to be delayed or stop, so I want a python file named delay.py which will delay the example.py process and execute.py which will execute the example.py process. What should the code in delay.py and execute.py be? What kind of python code should I write to delay or execute ongoing python process in Raspberry Pi?</p>
1
2016-08-27T14:32:28Z
39,183,322
<p>Every python script run on python.exe process. Just find the process name(it's better to find PID) that you want to pause or stop and by using system library you can stop that. But here is a link which solve your problem in Pi:</p> <p><a href="http://Every%20python%20script%20run%20on%20python.exe%20process.%20Just%20find%20the%20process%20name(it&#39;s%20better%20to%20find%20PID)%20%20that%20you%20want%20to%20pause%20or%20stop%20and%20by%20using%20system%20library%20you%20can%20stop%20that" rel="nofollow">Can't kill a python script</a></p>
0
2016-08-27T16:28:46Z
[ "python", "process", "raspberry-pi" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>head</code> as follows:</p> <pre><code>head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) </code></pre> <p>I'd like to add another node to the doubly-linked list, which I could do by</p> <pre><code>head.next.next.next = Node(data=8) </code></pre> <p>However, instead of writing ".next" three times, I would like to use a method which takes as input the number of times to call ".next" - that is, something like <code>head.next_n_times(3) = Node(data=8)</code> which would have the same effect. How could I achieve this?</p> <p>Here is what I've tried so far:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def next_n_times(self, n): next_node = self.next for i in range(n-1): next_node = next_node.next return next_node head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) data = 5 head.next_n_times(3) = Node(data=8) </code></pre> <p>However, I get the error message</p> <pre><code>File "sorted_insert_scratch.py", line 19 head.next_n_times(5) = Node(data=8) SyntaxError: can't assign to function call </code></pre> <p>It seems like the <code>next_n_times</code> method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p>
0
2016-08-27T14:40:04Z
39,182,432
<blockquote> <p>It seems like the next_n_times method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p> </blockquote> <p>What you get back is a <code>Node</code> object, and you want to set its <code>next</code> attribute: </p> <pre><code>head.next_n_times(3).next = Node(data=8) </code></pre> <p>To do what you want you have to change the syntax:</p> <pre><code>def append_at_next_n(self, n, node): next_node = self.next for i in range(n-1): next_node = next_node.next next_node.next = node return next_node </code></pre> <p>To make it work in your example:</p> <pre><code>head.append_at_next_n(3, Node(data=8)) </code></pre> <p>Note that <code>head.next.next.next</code> is currently <code>None</code>, as you only set <code>head.next.next</code>, so the above will raise an exception unless you add another node first.</p> <p>Expanding on this, however, you could make it kind of work with an actual property setter:</p> <pre><code>@property def appender(self): return self @appender.setter def append_at_next_n(self, args): n, node = args next_node = self.next for i in range(n-1): next_node = next_node.next next_node.next = node return next_node head.appender = (3, Node(2)) </code></pre> <p>It doesn't help readability though.</p>
1
2016-08-27T14:52:07Z
[ "python" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>head</code> as follows:</p> <pre><code>head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) </code></pre> <p>I'd like to add another node to the doubly-linked list, which I could do by</p> <pre><code>head.next.next.next = Node(data=8) </code></pre> <p>However, instead of writing ".next" three times, I would like to use a method which takes as input the number of times to call ".next" - that is, something like <code>head.next_n_times(3) = Node(data=8)</code> which would have the same effect. How could I achieve this?</p> <p>Here is what I've tried so far:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def next_n_times(self, n): next_node = self.next for i in range(n-1): next_node = next_node.next return next_node head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) data = 5 head.next_n_times(3) = Node(data=8) </code></pre> <p>However, I get the error message</p> <pre><code>File "sorted_insert_scratch.py", line 19 head.next_n_times(5) = Node(data=8) SyntaxError: can't assign to function call </code></pre> <p>It seems like the <code>next_n_times</code> method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p>
0
2016-08-27T14:40:04Z
39,182,492
<p>You're trying to implement the append method for the Node class. You can easily do so with recursion:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def append(self, node): if self.next: self.next.append(node) else: self.next = node self.next.prev = self </code></pre>
2
2016-08-27T14:59:06Z
[ "python" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>head</code> as follows:</p> <pre><code>head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) </code></pre> <p>I'd like to add another node to the doubly-linked list, which I could do by</p> <pre><code>head.next.next.next = Node(data=8) </code></pre> <p>However, instead of writing ".next" three times, I would like to use a method which takes as input the number of times to call ".next" - that is, something like <code>head.next_n_times(3) = Node(data=8)</code> which would have the same effect. How could I achieve this?</p> <p>Here is what I've tried so far:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def next_n_times(self, n): next_node = self.next for i in range(n-1): next_node = next_node.next return next_node head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) data = 5 head.next_n_times(3) = Node(data=8) </code></pre> <p>However, I get the error message</p> <pre><code>File "sorted_insert_scratch.py", line 19 head.next_n_times(5) = Node(data=8) SyntaxError: can't assign to function call </code></pre> <p>It seems like the <code>next_n_times</code> method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p>
0
2016-08-27T14:40:04Z
39,182,500
<p>Try this</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def next_n_times(self, n, value): next_node = self.next # loop to the penultimate Node for i in range(n-2): next_node = next_node.next # set that value to the value provided next_node.next = Node(value) if __name__ == '__main__': head = Node(data=4) head.next = Node(data=5) head.next.next = Node(data=6) head.prev = Node(data=2) data = 5 head.next_n_times(3, 8) # and to see if it worked... print head.next.next.next.data </code></pre> <p>Of course here were not checking if all the child nodes are present, so this will throw an error if head had only 1 child.</p>
0
2016-08-27T15:00:10Z
[ "python" ]
Indexing Matrix in TensorFlow
39,182,337
<p>For example, in Numpy I can get some values like this. </p> <pre><code>d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) # array([[0, 1, 2], # [3, 4, 5], # [6, 7, 8]]) d[[0, 1, 2], [2, 1, 0]] # array([2, 4, 6]) </code></pre> <p>So I can retrieve [2, 4, 6]. </p> <p>how can I do the same thing in TensorFlow?</p> <pre><code>x = tf.Variable([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) print sess.run([x[[0, 1, 2], [2,1,0]]])[0] </code></pre> <p>it raises TypeError </p> <pre><code>TypeError: Bad slice index [0, 1, 2] of type &lt;type 'list'&gt; </code></pre> <p>My Question is how can I get the same value through TensorFlow?</p> <pre><code>print sess.run([x[[0, 1, 2], [2,1,0]]])[0] </code></pre>
0
2016-08-27T14:41:29Z
39,182,415
<p>One solution I found is to use gather_nd function. </p> <pre><code>sess.run([tf.gather_nd(x, [[0, 2], [1, 1], [2, 0]])]) # [3 5 7] </code></pre> <p>Is there any other functions? a function more similar to Numpy in TensorFlow?</p>
0
2016-08-27T14:49:45Z
[ "python", "numpy", "neural-network", "tensorflow" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pygame # initialize pygame.init() # colors black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) # window size w_size = [700,500] main_screen = pygame.display.set_mode(w_size) # Window info pygame.display.set_caption("Cancer Cell") # manage screen update time clock=pygame.time.Clock() #background image bg_img = pygame.image.load("/img/bg_img.png").convert() # Main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # GAME LOGIC - BEGINNING # -------- DRAWINGS - BEGINNING -------- main_screen.blit(bg_img, [0,0]) # -------- DRAWINGS - END ---------- # update screen pygame.display.flip() clock.tick(20) # 20 FPS limit for loop. pygame.quit() </code></pre>
1
2016-08-27T14:46:44Z
39,182,491
<p>Your code work perfectly well on my platform. My platform: Scientific Linux 7 (RHEL 7) Python: 3.4.3 Pygame Version: 1.9.2b8 Window Manager: Gnome3</p> <p>There is also probably bug in your code. The "/img/bg_img.png" suggest absolute path, it possible, but very uncommon :).</p>
0
2016-08-27T14:58:59Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pygame # initialize pygame.init() # colors black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) # window size w_size = [700,500] main_screen = pygame.display.set_mode(w_size) # Window info pygame.display.set_caption("Cancer Cell") # manage screen update time clock=pygame.time.Clock() #background image bg_img = pygame.image.load("/img/bg_img.png").convert() # Main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # GAME LOGIC - BEGINNING # -------- DRAWINGS - BEGINNING -------- main_screen.blit(bg_img, [0,0]) # -------- DRAWINGS - END ---------- # update screen pygame.display.flip() clock.tick(20) # 20 FPS limit for loop. pygame.quit() </code></pre>
1
2016-08-27T14:46:44Z
39,182,504
<p>Works pretty nicely for me. See the demo below:</p> <p><a href="http://i.stack.imgur.com/0CsC8.gif" rel="nofollow"><img src="http://i.stack.imgur.com/0CsC8.gif" alt="enter image description here"></a></p>
0
2016-08-27T15:01:08Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pygame # initialize pygame.init() # colors black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) # window size w_size = [700,500] main_screen = pygame.display.set_mode(w_size) # Window info pygame.display.set_caption("Cancer Cell") # manage screen update time clock=pygame.time.Clock() #background image bg_img = pygame.image.load("/img/bg_img.png").convert() # Main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # GAME LOGIC - BEGINNING # -------- DRAWINGS - BEGINNING -------- main_screen.blit(bg_img, [0,0]) # -------- DRAWINGS - END ---------- # update screen pygame.display.flip() clock.tick(20) # 20 FPS limit for loop. pygame.quit() </code></pre>
1
2016-08-27T14:46:44Z
39,182,635
<p>Not only does your code work as expected on linux Mate 17, python 2.7.6 but it also works with <code>sys.exit()</code> instead of <code>pygame.quit()</code> or nothing at all i.e. no <code>sys.exit()</code> or <code>pygame.quit()</code></p>
0
2016-08-27T15:13:26Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pygame # initialize pygame.init() # colors black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) # window size w_size = [700,500] main_screen = pygame.display.set_mode(w_size) # Window info pygame.display.set_caption("Cancer Cell") # manage screen update time clock=pygame.time.Clock() #background image bg_img = pygame.image.load("/img/bg_img.png").convert() # Main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # GAME LOGIC - BEGINNING # -------- DRAWINGS - BEGINNING -------- main_screen.blit(bg_img, [0,0]) # -------- DRAWINGS - END ---------- # update screen pygame.display.flip() clock.tick(20) # 20 FPS limit for loop. pygame.quit() </code></pre>
1
2016-08-27T14:46:44Z
39,182,681
<p>So it turns out that the IDLE is what was causing the problem... I tried to run the code from commandline and it worked perfectly!</p> <p>The IDLE that I (was) using is called Wing101.</p>
0
2016-08-27T15:18:46Z
[ "python", "pygame" ]
tar files and download with flask app
39,182,405
<p>I have one tex file and three images and I want that the user can click a button and download all three of them. It would be ideal if the four files would be as one tar file. My download works as follows right now</p> <pre><code>@app.route('/download_tex', methods=['GET', 'POST']) @login_required def download_tex(): latext_text = render_template('get_lates.html') filename = 'test' response = make_response(latext_text) response.headers["Content-Disposition"] = "attachment; filename=%s.tex" % filename return response </code></pre> <p>this works fine for the tex file, but how can I tar up files within the flask app and send the tar file instead?</p> <p>EDIT: Ok thanks to the comment below I came up with this code </p> <pre><code>latext_text = render_template('get_latex.html') latex_file = open(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username, "w") latex_file.write(latext_text) latex_file.close() filename = 'tarfile_%s.tar.gz' % current_user.username filepath = basedir + '/app/static/statistics/%s' % filename tar = tarfile.open(filepath, "w:gz") tar.add(basedir + '/app/static/statistics/image1.png') tar.add(basedir + '/app/static/statistics/image2.png') tar.add(basedir + '/app/static/statistics/image3.png') tar.add(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username) tar.close() </code></pre> <p>but how can I now download that tar file with the browser?</p>
1
2016-08-27T14:49:16Z
39,183,457
<p>You should use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory" rel="nofollow">send_from_directory</a> method that Flask provides for this =) It is the perfect use case for what you're doing.</p> <p>What you can do is something like this:</p> <pre><code>from flask import send_from_directory # code here ... filename = 'tarfile_%s.tar.gz' % current_user.username filedir = basedir + '/app/static/statistics/' # tar code here ... return send_from_directory(filedir, filename, as_attachment=True) </code></pre> <p>That will handle all of the downloading bits for you in a clean way.</p>
1
2016-08-27T16:43:12Z
[ "python", "flask" ]
Catch Google Endpoint Response Error
39,182,536
<p>It's very hard to track Google Endpoints error, which raised at the time response:</p> <pre><code>Encountered unexpected error from ProtoRPC method implementation: ValidationError (Message MatchCenterResponseMessage is missing required field sport) (/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/wsgi/service.py:191) Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/wsgi/service.py", line 182, in protorpc_service_app encoded_response = protocol.encode_message(response) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/remote.py", line 1109, in encode_message return self.__protocol.encode_message(message) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/protojson.py", line 179, in encode_message message.check_initialized() File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/messages.py", line 769, in check_initialized (type(self).__name__, name)) ValidationError: Message ResponseMessage is missing required field xyz </code></pre> <p>Is there any ways to catch this exception from application? Instead of from Google Endpoint native code.</p> <p>Thanks</p>
0
2016-08-27T15:03:58Z
39,183,235
<p>You can use try except structure to catch the error. Also tracing may help you alot. </p> <pre><code>try: //your code Except ValidationError: raiseError </code></pre>
0
2016-08-27T16:19:06Z
[ "python", "google-app-engine", "google-cloud-endpoints" ]
Python Flask Login login_required redirecting
39,182,650
<p>I am working on a Flask app and using Flask-Login for authentication. Everything is set up and running. However when the user logins in and attempts to visit a page that requires login, they are redirected to the login page. </p> <p>When watching the console, I get a 200 for the GET login page, a 200 for the POST on the login, a 302 from the login page to the home page, and then another 302 from the homepage back to login.</p> <p>See code below.</p> <pre><code>from flask import (Flask, render_template, g, flash, redirect, url_for, request) from flask_bcrypt import check_password_hash from flask_login import (LoginManager, UserMixin, login_required, login_user, logout_user, current_user) import models import forms application = Flask(__name__) application.secret_key = "xxx-xxx-xxx-xxx" login_manager = LoginManager() login_manager.init_app(application) login_manager.login_view = "login" @application.before_request def before_request(): g.db = models.DATABASE g.db.connect() g.user = current_user @application.after_request def after_request(response): g.db.close() return response @login_manager.user_loader def load_user(email): try: return models.User.select().where( models.User.email == email).get() except models.DoesNotExist: return None @application.route("/register", methods=['GET', 'POST']) def register(): form = forms.RegisterForm() if form.validate_on_submit(): flash("Yay! You registered!", "success") models.User.create_user( email = form.email.data, password = form.password.data ) return redirect(url_for('home')) return render_template('register.html',form=form) @application.route("/login", methods=['GET', 'POST']) def login(): form = forms.LoginForm() if form.validate_on_submit(): next = request.args.get('next') try: user = models.User.get(models.User.email == form.email.data) except models.DoesNotExist: flash("Your email or password doesn't match!", "error") else: if check_password_hash(user.password, form.password.data): login_user(user, remember=True) flash("Welcome back!", "success") return redirect(next or url_for("home")) else: flash("Your email or password doesn't match!", "error") return render_template("login.html", form=form) @application.route("/logout") @login_required def logout(): logout_user() flash("You've been logged out!", "success") return redirect(url_for("home")) @application.route("/") @login_required def home(): return render_template("home.html") if __name__ == "__main__": models.initialize() application.run(host='0.0.0.0') </code></pre> <p>Here is the model:</p> <pre><code>import datetime from flask_login import UserMixin from flask_bcrypt import generate_password_hash, check_password_hash from peewee import * DATABASE = MySQLDatabase("fakedatabasename", host="fakehostname", user="fakeusername", password="fakepassword") class BaseModel(Model): class Meta: database = DATABASE class Preachers(BaseModel): preacher_id = PrimaryKeyField() preacher_first_name = CharField(max_length=27) preacher_last_name = CharField(max_length=27) preacher_email = CharField() class Sermons(BaseModel): sermon_id = PrimaryKeyField() sermon_title = CharField(max_length=27) sermon_description = CharField(max_length=140) sermon_date = DateTimeField(default=datetime.datetime.now()) sermon_preacher_id = IntegerField() sermon_video_uri = CharField(max_length=255) class User(UserMixin,BaseModel): user_id = PrimaryKeyField() email = CharField(index=True, unique=True) password = CharField() date_created = DateTimeField(default=datetime.datetime.now()) @classmethod def create_user(cls, email, password): try: cls.create( email = email, password = generate_password_hash(password) ) except IntegrityError: raise ValueError("User already exists") def initialize(): DATABASE.connect() DATABASE.create_tables([Preachers, Sermons, User], safe=True) DATABASE.close() </code></pre>
2
2016-08-27T15:15:21Z
39,307,130
<p>So it turns out that when working with Peewee and Flask-Login, you need to let Peewee supply its default primary key for the User model instead of using a custom one. Removing <code>user_id = PrimaryKeyField()</code>, dropping the table, and restarting fixed it.</p>
0
2016-09-03T12:55:16Z
[ "python", "flask", "flask-login" ]
Why if the id = '0' in "InlineQueryResultArticle" the element chosen doesn't trigger the "on_chosen_inline_result" code?
39,182,676
<p>I'm new to Python and new to Stack Overflow, sorry for my mistakes...</p> <p>I'm using Telepot to write a bot for Telegram.<br> When dealing with inline results I can only make the code in <code>on_chosen_inline_result</code> execute for every article I choose other than the first created.</p> <pre><code>def on_inline_query(msg): query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query') tastiera_inline = InlineKeyboardMarkup(*some_keyboard*) articles = [] if query_string: found_conte = fun.get_conta(titolo=query_string) if found_conte == 1: return for conta_inline in found_conte: articles.append(InlineQueryResultArticle( id=str(conta_inline['id']), title=conta_inline['titolo'], input_message_content=InputTextMessageContent(*some_content*), reply_markup=tastiera_inline, description=conta_inline['testo'], thumb_url=*some_url*, )) else: if fun.get_conta('all') == 1: return for conta_inline in fun.get_conta('all'): articles.append(InlineQueryResultArticle( id=str(conta_inline['id']), title=conta_inline['titolo'], input_message_content=InputTextMessageContent(*some_content*), reply_markup=tastiera_inline, description=conta_inline['testo'], thumb_url=*some_url*, )) bot.answerInlineQuery(query_id, articles) def on_chosen_inline_result(msg): print(msg) bot = telepot.Bot(TOKEN) bot.message_loop({'chat': on_chat_message, 'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result }, run_forever='Listening ...') </code></pre> <p><code>print(msg)</code> is working fine for every article I choose from the list of answers to the inline query except for the first one created. I am really confused...</p> <p>What is really confusing is that I don't think to have the control on what happens when I choose an article from the list in Telegram, so it seems strange that sometimes it triggers the <code>on_chosen_inline_result</code> code and other times it doesn't. </p> <p>EDIT: It seems like if <code>id='0'</code> in <code>InlineQueryResultArticle</code> the chosen result doesn't trigger the code inside <code>on_chosen_inline_result</code>, but I'm not 100% sure this is the cause, and I really don't know why, anyway...</p> <p>PS: I don't know how much code is needed to understand the problem without copying everything here. I can surely edit the question and add more code if needed.</p>
2
2016-08-27T15:18:30Z
39,188,148
<p>From my own test, it seems your suspicion is correct. I have tried a variety of id strings and chosen each of them in turn:</p> <ul> <li><code>00</code> → Yes (<code>chosen_inline_result</code> gotten)</li> <li><code>$0</code> → Yes</li> <li><code>0</code> → No</li> <li><code>1</code> → Yes</li> </ul> <p>As the author of telepot, I can't think of anywhere a result id of <code>0</code> may get filtered out inadvertently. So I am presuming it's a Telegram issue.</p> <p>As illustrated above, it's easy to get around. You can prepend almost any character in front to get back the <code>chosen_inline_result</code>.</p> <p>In case anyone is interested, here's my testing code:</p> <pre><code>import sys import threading import telepot from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent def on_inline_query(msg): def compute(): query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query') print('%s: Computing for: %s' % (threading.current_thread().name, query_string)) articles = [InlineQueryResultArticle( id='00', title='ID=00', input_message_content=InputTextMessageContent( message_text='ID=00')), InlineQueryResultArticle( id='$0', title='ID=$0', input_message_content=InputTextMessageContent( message_text='ID=$0')), InlineQueryResultArticle( id='0', title='ID=0', input_message_content=InputTextMessageContent( message_text='ID=0')), InlineQueryResultArticle( id='1', title='ID=1', input_message_content=InputTextMessageContent( message_text='ID=1')),] return dict(results=articles) answerer.answer(msg, compute) def on_chosen_inline_result(msg): result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print('Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] # get token from command-line bot = telepot.Bot(TOKEN) answerer = telepot.helper.Answerer(bot) bot.message_loop({'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result}, run_forever='Listening ...') </code></pre>
1
2016-08-28T04:56:57Z
[ "python", "telegram-bot" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentation, I got that the roots of this equation are approximately equal to 0.86322414 and 0.9961936895432034 (we know there are at most 2 roots because the function has one inflection point in this interval):</p> <pre><code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02) print(fsolve(f1, 0.5)) print(f1(0.99)) print(f1(0.999)) print(brentq(f1, 0.99, 0.999)) </code></pre> <p>Output: </p> <pre><code>[ 0.86322414] -0.016332046983897452 0.025008640855473052 0.9961936895432034 </code></pre> <p>The issue here is that in order for brentq to work, the values of the function must be of opposite signs at the specified endpoints. Furthermore, when I started fsolve at values of <code>x</code> close to 1, I got runtime warning messages:</p> <pre><code>print(fsolve(f1, 0.97)) print(fsolve(f1, 0.98)) </code></pre> <p>Output:</p> <pre><code>[ 0.97] [ 0.98] C:/Users/Alexander/Google Drive/Programming/Projects/Root Finding/roots.py:6: RuntimeWarning: invalid value encountered in power C:\Users\Alexander\Anaconda3\lib\site-packages\scipy\optimize\minpack.py:161: RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last ten iterations. </code></pre> <p>Does anyone if there is a more systematic way to solve for roots of this equation, and why fsolve is not working on <code>x = 0.97, 0.98</code>?</p>
0
2016-08-27T15:23:07Z
39,186,066
<p>fsolve does not support root-finding on an interval. It likely wanders off to either x&lt;0 or x>1, hence RuntimeWarning (once) and garbage for the answer. You can check it by instrumenting your function with print(x).</p> <p>Brentq's behavior is undefined if the interval contains more then one root.</p> <p>If you know the inflection point, or know that there's only one, then you can find it via brentq and use it to bracket your two roots.</p>
2
2016-08-27T21:52:11Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentation, I got that the roots of this equation are approximately equal to 0.86322414 and 0.9961936895432034 (we know there are at most 2 roots because the function has one inflection point in this interval):</p> <pre><code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02) print(fsolve(f1, 0.5)) print(f1(0.99)) print(f1(0.999)) print(brentq(f1, 0.99, 0.999)) </code></pre> <p>Output: </p> <pre><code>[ 0.86322414] -0.016332046983897452 0.025008640855473052 0.9961936895432034 </code></pre> <p>The issue here is that in order for brentq to work, the values of the function must be of opposite signs at the specified endpoints. Furthermore, when I started fsolve at values of <code>x</code> close to 1, I got runtime warning messages:</p> <pre><code>print(fsolve(f1, 0.97)) print(fsolve(f1, 0.98)) </code></pre> <p>Output:</p> <pre><code>[ 0.97] [ 0.98] C:/Users/Alexander/Google Drive/Programming/Projects/Root Finding/roots.py:6: RuntimeWarning: invalid value encountered in power C:\Users\Alexander\Anaconda3\lib\site-packages\scipy\optimize\minpack.py:161: RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last ten iterations. </code></pre> <p>Does anyone if there is a more systematic way to solve for roots of this equation, and why fsolve is not working on <code>x = 0.97, 0.98</code>?</p>
0
2016-08-27T15:23:07Z
39,188,106
<p>If you take the derivative of your function and set it equal to 0, after a little algebra you'll find that the derivative is 0 at x0 = 0.5/0.52. (In a calculus class, this point is called a <em>critical point</em>, not an inflection point.) The function has a minimum at this point, and the value there is negative. The values at x=0 and x=1 are positive, so you can use [0, x0] and [x0, 1] as bracketing intervals in <code>brentq</code>:</p> <pre><code>In [17]: from scipy.optimize import brentq In [18]: f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02) In [19]: x0 = 0.5/0.52 In [20]: brentq(f1, 0, x0) Out[20]: 0.8632241390303161 In [21]: brentq(f1, x0, 1) Out[21]: 0.9961936895432096 </code></pre>
2
2016-08-28T04:47:04Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentation, I got that the roots of this equation are approximately equal to 0.86322414 and 0.9961936895432034 (we know there are at most 2 roots because the function has one inflection point in this interval):</p> <pre><code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02) print(fsolve(f1, 0.5)) print(f1(0.99)) print(f1(0.999)) print(brentq(f1, 0.99, 0.999)) </code></pre> <p>Output: </p> <pre><code>[ 0.86322414] -0.016332046983897452 0.025008640855473052 0.9961936895432034 </code></pre> <p>The issue here is that in order for brentq to work, the values of the function must be of opposite signs at the specified endpoints. Furthermore, when I started fsolve at values of <code>x</code> close to 1, I got runtime warning messages:</p> <pre><code>print(fsolve(f1, 0.97)) print(fsolve(f1, 0.98)) </code></pre> <p>Output:</p> <pre><code>[ 0.97] [ 0.98] C:/Users/Alexander/Google Drive/Programming/Projects/Root Finding/roots.py:6: RuntimeWarning: invalid value encountered in power C:\Users\Alexander\Anaconda3\lib\site-packages\scipy\optimize\minpack.py:161: RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last ten iterations. </code></pre> <p>Does anyone if there is a more systematic way to solve for roots of this equation, and why fsolve is not working on <code>x = 0.97, 0.98</code>?</p>
0
2016-08-27T15:23:07Z
39,194,788
<p>As you already know, a direct answer to part of your question is that fsolve doesn't find a root in the interval [0.97,0.98] because there's no root there. As for a systematic way, why not use <strong>plot</strong>?</p> <p>Once you've defined the function as a <strong>lambda</strong>, ready for use with Brent or various other routines, you can just copy and paste the substring you need into a call to <strong>plot</strong> and indicate the interval of interest. If one of the roots is a bit obscure then broaden that part of the x-axis.</p> <p><a href="http://i.stack.imgur.com/3vg8T.png" rel="nofollow"><img src="http://i.stack.imgur.com/3vg8T.png" alt="Function to study"></a></p> <p>Here's some typical code in this case.</p> <p><a href="http://i.stack.imgur.com/4fTme.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/4fTme.jpg" alt="Produce plot and find roots"></a></p>
1
2016-08-28T19:01:47Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Applying Decay Factor to Return Data in Pandas and Saving as New Variable
39,182,747
<p>I have return data for stocks (thousands of them but am only showing 4 here) as below:</p> <pre><code>In[3]:ret Out[3]: Symbol AAPL DE IBM MSFT Date 2016-01-19 NaN NaN NaN NaN 2016-01-20 -0.021780 -0.019701 -0.078557 -0.019177 2016-01-21 0.016271 0.014681 0.021823 0.024440 2016-01-22 0.036128 0.034555 0.009910 0.019085 2016-01-25 0.008539 -0.026477 -0.001068 0.007608 2016-01-26 -0.011491 -0.000907 0.004933 -0.001936 2016-01-27 -0.048231 0.021428 -0.013007 -0.010279 ... ... ... ... 2016-08-16 0.010455 0.010135 -0.006738 -0.005712 2016-08-17 -0.007966 -0.006432 -0.005290 -0.000698 2016-08-18 0.006277 -0.006603 0.003754 0.000699 2016-08-19 -0.006054 0.034406 -0.005735 -0.001222 2016-08-22 -0.004707 0.091092 -0.002445 0.001049 2016-08-23 0.006305 0.007621 0.006913 0.010304 [152 rows x 4 columns] </code></pre> <p>I need to weight the data by applying a 0.97 decay factor where ret(i) = ret(i)*(0.97**i) where ret(0) is my first data-point and is from the most recent day (2016-08-23) and would effectively be unchanged as (i) would be 0</p> <p>I then need to have the ret variable saved as ret_decay</p> <p>any assistance would be greatly appreciated.</p> <p><strong>ADDED INFORMATION DATA and CODE</strong></p> <p><strong>CloseWeightmini.csv data:</strong></p> <pre><code>Date Symbol ClosingPrice Weight 8/16/2016 AAPL 109.21 0.0006944 8/17/2016 AAPL 108.34 0.0006944 8/18/2016 AAPL 109.02 0.0006944 8/19/2016 AAPL 108.36 0.0006944 8/22/2016 AAPL 107.85 0.0006944 8/23/2016 AAPL 108.53 0.0006944 8/16/2016 DE 77.74 -0.0007157 8/17/2016 DE 77.24 -0.0007157 8/18/2016 DE 76.73 -0.0007157 8/19/2016 DE 79.37 -0.0007157 8/22/2016 DE 86.6 -0.0007157 8/23/2016 DE 87.26 -0.0007157 8/16/2016 IBM 160.69 -0.0001277 8/17/2016 IBM 159.84 -0.0001277 8/18/2016 IBM 160.4401 -0.0001277 8/19/2016 IBM 159.52 -0.0001277 8/22/2016 IBM 159.13 -0.0001277 8/23/2016 IBM 160.23 -0.0001277 8/16/2016 MSFT 57.27 0.00009 8/17/2016 MSFT 57.23 0.00009 8/18/2016 MSFT 57.27 0.00009 8/19/2016 MSFT 57.2 0.00009 8/22/2016 MSFT 57.26 0.00009 8/23/2016 MSFT 57.85 0.00009 </code></pre> <p><strong>here is my code:</strong></p> <pre><code>import numpy as np import pandas as pd import pandas.io.data as web from scipy.stats import norm import datetime as dt Days = 1 Value=1e6 # $1,000,000 CI=0.99 # set the confidence interval decay = 0.97 df=pd.read_csv('CloseWeightsmini.csv') df['Date'] = pd.to_datetime(df['Date']) df=df.drop_duplicates(['Date','Symbol'], keep='first') df2=df.iloc[:,0:3].pivot('Date', 'Symbol', 'ClosingPrice') df3=df.iloc[:,[1,3]].drop_duplicates().set_index('Symbol') df4=df.iloc[:,[1,3]].drop_duplicates().reset_index(drop=True) tickers=df4['Symbol'] numbers=len(tickers) data=df2 ret=data/data.shift(1)-1 # calculate the simple returns </code></pre> <p>The rest of my code works, I just need to have the decay factor (0.97 in this case) applied to each date such that the most recent data has more weight as i outlined in the original post.</p>
1
2016-08-27T15:26:33Z
39,183,014
<p>Adding column row_index:</p> <pre><code>In [229]: df['row_index'] = df.apply(lambda x: x.name, axis = 1) In [230]: df Out[230]: Date AAPL DE IBM MSFT row_index 0 2016-01-19 NaN NaN NaN NaN 0 1 2016-01-20 -0.021780 -0.019701 -0.078557 -0.019177 1 2 2016-01-21 0.016271 0.014681 0.021823 0.024440 2 3 2016-01-22 0.036128 0.034555 0.009910 0.019085 3 4 2016-01-25 0.008539 -0.026477 -0.001068 0.007608 4 5 2016-01-26 -0.011491 -0.000907 0.004933 -0.001936 5 6 2016-01-27 -0.048231 0.021428 -0.013007 -0.010279 6 </code></pre> <p>Apply decay function to a set of columns:</p> <pre><code>In [231]: df[df.columns[1:5]].apply(lambda x: df[x.name]*(0.97**df['row_index'])) Out[231]: AAPL DE IBM MSFT 0 NaN NaN NaN NaN 1 -0.021127 -0.019110 -0.076200 -0.018602 2 0.015309 0.013813 0.020533 0.022996 3 0.032973 0.031537 0.009045 0.017418 4 0.007560 -0.023440 -0.000945 0.006735 5 -0.009868 -0.000779 0.004236 -0.001663 6 -0.040175 0.017849 -0.010834 -0.008562 </code></pre> <p>Probably, ignore the first row?: </p> <pre><code>In [232]: df[df.columns[1:5]].apply(lambda x: df[x.name]*(0.97**(df['row_index'] - 1))) Out[232]: AAPL DE IBM MSFT 0 NaN NaN NaN NaN 1 -0.021780 -0.019701 -0.078557 -0.019177 2 0.015783 0.014241 0.021168 0.023707 3 0.033993 0.032513 0.009324 0.017957 4 0.007793 -0.024165 -0.000975 0.006944 5 -0.010173 -0.000803 0.004367 -0.001714 6 -0.041418 0.018401 -0.011170 -0.008827 </code></pre> <p>If the index should start from bottom:</p> <pre><code>In [262]: newdf = df[df.columns[1:5]].apply(lambda x: df[x.name]*(0.97**(len(df) - df['row_index'] - 1))) In [263]: newdf['Date'] = df['Date'] In [264]: newdf Out[264]: AAPL DE IBM MSFT Date 0 NaN NaN NaN NaN 2016-01-19 1 -0.018703 -0.016918 -0.067460 -0.016468 2016-01-20 2 0.014405 0.012997 0.019320 0.021637 2016-01-21 3 0.032973 0.031537 0.009045 0.017418 2016-01-22 4 0.008034 -0.024912 -0.001005 0.007158 2016-01-25 5 -0.011146 -0.000880 0.004785 -0.001878 2016-01-26 6 -0.048231 0.021428 -0.013007 -0.010279 2016-01-27 </code></pre>
1
2016-08-27T15:56:18Z
[ "python", "pandas" ]
Applying Decay Factor to Return Data in Pandas and Saving as New Variable
39,182,747
<p>I have return data for stocks (thousands of them but am only showing 4 here) as below:</p> <pre><code>In[3]:ret Out[3]: Symbol AAPL DE IBM MSFT Date 2016-01-19 NaN NaN NaN NaN 2016-01-20 -0.021780 -0.019701 -0.078557 -0.019177 2016-01-21 0.016271 0.014681 0.021823 0.024440 2016-01-22 0.036128 0.034555 0.009910 0.019085 2016-01-25 0.008539 -0.026477 -0.001068 0.007608 2016-01-26 -0.011491 -0.000907 0.004933 -0.001936 2016-01-27 -0.048231 0.021428 -0.013007 -0.010279 ... ... ... ... 2016-08-16 0.010455 0.010135 -0.006738 -0.005712 2016-08-17 -0.007966 -0.006432 -0.005290 -0.000698 2016-08-18 0.006277 -0.006603 0.003754 0.000699 2016-08-19 -0.006054 0.034406 -0.005735 -0.001222 2016-08-22 -0.004707 0.091092 -0.002445 0.001049 2016-08-23 0.006305 0.007621 0.006913 0.010304 [152 rows x 4 columns] </code></pre> <p>I need to weight the data by applying a 0.97 decay factor where ret(i) = ret(i)*(0.97**i) where ret(0) is my first data-point and is from the most recent day (2016-08-23) and would effectively be unchanged as (i) would be 0</p> <p>I then need to have the ret variable saved as ret_decay</p> <p>any assistance would be greatly appreciated.</p> <p><strong>ADDED INFORMATION DATA and CODE</strong></p> <p><strong>CloseWeightmini.csv data:</strong></p> <pre><code>Date Symbol ClosingPrice Weight 8/16/2016 AAPL 109.21 0.0006944 8/17/2016 AAPL 108.34 0.0006944 8/18/2016 AAPL 109.02 0.0006944 8/19/2016 AAPL 108.36 0.0006944 8/22/2016 AAPL 107.85 0.0006944 8/23/2016 AAPL 108.53 0.0006944 8/16/2016 DE 77.74 -0.0007157 8/17/2016 DE 77.24 -0.0007157 8/18/2016 DE 76.73 -0.0007157 8/19/2016 DE 79.37 -0.0007157 8/22/2016 DE 86.6 -0.0007157 8/23/2016 DE 87.26 -0.0007157 8/16/2016 IBM 160.69 -0.0001277 8/17/2016 IBM 159.84 -0.0001277 8/18/2016 IBM 160.4401 -0.0001277 8/19/2016 IBM 159.52 -0.0001277 8/22/2016 IBM 159.13 -0.0001277 8/23/2016 IBM 160.23 -0.0001277 8/16/2016 MSFT 57.27 0.00009 8/17/2016 MSFT 57.23 0.00009 8/18/2016 MSFT 57.27 0.00009 8/19/2016 MSFT 57.2 0.00009 8/22/2016 MSFT 57.26 0.00009 8/23/2016 MSFT 57.85 0.00009 </code></pre> <p><strong>here is my code:</strong></p> <pre><code>import numpy as np import pandas as pd import pandas.io.data as web from scipy.stats import norm import datetime as dt Days = 1 Value=1e6 # $1,000,000 CI=0.99 # set the confidence interval decay = 0.97 df=pd.read_csv('CloseWeightsmini.csv') df['Date'] = pd.to_datetime(df['Date']) df=df.drop_duplicates(['Date','Symbol'], keep='first') df2=df.iloc[:,0:3].pivot('Date', 'Symbol', 'ClosingPrice') df3=df.iloc[:,[1,3]].drop_duplicates().set_index('Symbol') df4=df.iloc[:,[1,3]].drop_duplicates().reset_index(drop=True) tickers=df4['Symbol'] numbers=len(tickers) data=df2 ret=data/data.shift(1)-1 # calculate the simple returns </code></pre> <p>The rest of my code works, I just need to have the decay factor (0.97 in this case) applied to each date such that the most recent data has more weight as i outlined in the original post.</p>
1
2016-08-27T15:26:33Z
39,184,540
<p>Try This: </p> <pre><code>df = df.set_index("Date") retFac = np.fromfunction(lambda i,j : .97**(i), df.values.shape)[::-1] df*retFac df['ret_decay'] = retFac[:,0] df AAPL DE IBM MSFT ret_decay Date 2016-01-19 NaN NaN NaN NaN 0.693842 2016-01-20 -0.021780 -0.019701 -0.078557 -0.019177 0.715301 2016-01-21 0.016271 0.014681 0.021823 0.024440 0.737424 2016-01-22 0.036128 0.034555 0.009910 0.019085 0.760231 2016-01-25 0.008539 -0.026477 -0.001068 0.007608 0.783743 2016-01-26 -0.011491 -0.000907 0.004933 -0.001936 0.807983 2016-01-27 -0.048231 0.021428 -0.013007 -0.010279 0.832972 2016-08-16 0.010455 0.010135 -0.006738 -0.005712 0.858734 2016-08-17 -0.007966 -0.006432 -0.005290 -0.000698 0.885293 2016-08-18 0.006277 -0.006603 0.003754 0.000699 0.912673 2016-08-19 -0.006054 0.034406 -0.005735 -0.001222 0.940900 2016-08-22 -0.004707 0.091092 -0.002445 0.001049 0.970000 2016-08-23 0.006305 0.007621 0.006913 0.010304 1.000000 </code></pre> <p>Using the newly added code: and </p> <pre><code>retFac = np.fromfunction(lambda i,j : .97**(i), ret.values.shape)[::-1] ret*retFac ret['ret_decay'] = retFac[:,0] ret Symbol AAPL DE IBM MSFT ret_decay Date 2016-08-16 NaN NaN NaN NaN 0.858734 2016-08-17 -0.007966 -0.006432 -0.005290 -0.000698 0.885293 2016-08-18 0.006277 -0.006603 0.003754 0.000699 0.912673 2016-08-19 -0.006054 0.034406 -0.005735 -0.001222 0.940900 2016-08-22 -0.004707 0.091092 -0.002445 0.001049 0.970000 2016-08-23 0.006305 0.007621 0.006913 0.010304 1.000000 </code></pre>
0
2016-08-27T18:41:10Z
[ "python", "pandas" ]
Moving Character in pygame Without Repeatedly Copying Image
39,182,813
<p>My character, like most characters, is supposed to be repeatedly replaced by the same image a few pixels over to simulate movement. Instead, my code causes the image to be copied when I move it, and right now it's more like a drawing application than a moving character. Can someone please tell me why this is happening and what can be done to replace the previous image? Thanks in advance.</p> <pre><code>import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF=pygame.display.set_mode((800,800)) pygame.display.set_caption('Hola Amigos!') pixel_one=pygame.image.load('pixel_one.png') pixel_one=pygame.transform.scale(pixel_one, (5,5)) def pixel(pixel_onex,pixel_oney): DISPLAYSURF.blit(pixel_one, (pixel_onex, pixel_oney)) pixel_onex=10 pixel_oney=10 x_change=0 y_change=0 while True: #main game loop for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 elif event.key == pygame.K_UP: y_change = -5 elif event.key == pygame.K_DOWN: y_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or pygame.K_RIGHT or pygame.K_UP or pygame.K_DOWN: x_change=0 y_change=0 if event.type==QUIT: pygame.quit() sys.exit() pixel_onex += x_change pixel_oney += y_change pixel(pixel_onex,pixel_oney) pygame.display.update() </code></pre>
1
2016-08-27T15:33:27Z
39,183,251
<p>Before you enter the main loop, add a statement like</p> <pre><code>background = pygame.Surface(DISPLAYSURF.get_size()) </code></pre> <p>and then blit background onto DISPLAYSURF. At each iteration, after everything has been updated but before anything else has been drawn, blit your background onto the DISPLAYSURF to create a clean surface.</p>
1
2016-08-27T16:20:46Z
[ "python", "pygame" ]
Round-off / round-up criteria in Python
39,182,861
<p>I'm porting a MATLAB code to Python 3.5.1 and I found a float round-off issue.</p> <p>In MATLAB, the following number is rounded <strong>up</strong> to the 6th decimal place:</p> <pre><code>fprintf(1,'%f', -67.6640625); -67.664063 </code></pre> <p>In Python, on the other hand, the following number is rounded <strong>off</strong> to the 6th decimal place:</p> <pre><code>print('%f' % -67.6640625) -67.664062 </code></pre> <p>Interestingly enough, if the number is '-67.6000625', then it is rounded <strong>up</strong> even in Python:</p> <pre><code>print('%f' % -67.6000625) -67.600063 </code></pre> <p>... Why does this happen? What are the criteria to round-off/up in Python? (I believe this has something to do with handling hexadecimal values.)</p> <p>More importantly, how can I prevent this difference? I'm supposed to create a python code which can reproduce exactly the same output as MATLAB produces.</p>
5
2016-08-27T15:37:33Z
39,187,125
<p>The reason for the python behavior has to do with how floating point numbers are stored in a computer and the standardized rounding rules defined by IEEE, which defined the standard number formats and mathematical operations used on pretty much all modern computers.</p> <p>The need to store numbers efficiently in binary on a computer has lead computers to use floating-point numbers. These numbers are easy for processors to work with, but have the disadvantage that many decimal numbers <a href="https://docs.python.org/3/tutorial/floatingpoint.html#representation-error" rel="nofollow">cannot be exactly represented</a>. This results in numbers sometimes being a little off from what we think they should be.</p> <p>The situation becomes a bit clearer if we expand the values in Python, rather than truncating them:</p> <pre><code>&gt;&gt;&gt; print('%.20f' % -67.6640625) -67.66406250000000000000 &gt;&gt;&gt; print('%.20f' % -67.6000625) -67.60006250000000704858 </code></pre> <p>So as you can see, <code>-67.6640625</code> is a number that can be exactly represented, but <code>-67.6000625</code> isn't, it is actually a little bigger. The default rounding mode <a href="https://en.wikipedia.org/wiki/IEEE_floating_point#Rounding_rules" rel="nofollow">defined by the IEEE stanard</a> for floating-point numbers says that anything above <code>5</code> should be rounded up, anything below should be rounded down. So for the case of <code>-67.6000625</code>, it is actualy <code>5</code> plus a small amount, so it is rounded up. However, in the case of <code>-67.6640625</code>, it is exactly equal to five, so a tiebreak rule comes into play. The default tiebreaker rule is round to the nearest even number. Since <code>2</code> is the nearest event number, it rounds down to two.</p> <p>So Python is following the approach recommended by the floating-point standard. The question, then, is why your version of MATLAB <em>doesn't</em> do this. I tried it on my computer with 64bit MATLAB R2016a, and I got the same result as in Python:</p> <pre><code>&gt;&gt; fprintf(1,'%f', -67.6640625) -67.664062&gt;&gt; </code></pre> <p>So it seems like MATLAB was, at some point, using a different rounding approach (perhaps a non-standard approach, perhaps one of the alternatives specified in the standard), and has since switched to follow the same rules as everyone else.</p>
4
2016-08-28T01:02:08Z
[ "python", "matlab", "rounding" ]
How to define start value for ID column in SQLAlchemy for SQLServer?
39,182,924
<p>I interfacing SQLAlchemy between Flask and SQLServer.</p> <p>I have an ID column which I would like to start from 10000. I couldn't find the answer.</p> <p>Below is the SQL code, I am trying to convert to SQLAlchemy.</p> <p>Please let me know.</p> <p>Thx</p> <pre><code>create TABLE [dbo].[Product]( [ID] [int] IDENTITY(**10000**,1) NOT NULL, [Name] [varchar](200) NOT NULL, [Description] [varchar](500) NULL, [Brand] [varchar](500) NOT NULL, [Price] [real] NOT NULL, [Qty] [int] NOT NULL, [ProductFilenamePrefix] [varchar](200) NOT NULL, PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY], UNIQUE NONCLUSTERED ( [Name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre>
1
2016-08-27T15:45:23Z
39,207,014
<p>You'll need to do some changes after SQLAlchemy creates the table, as shown in the links above for MySQL, but with SQL Server.</p> <pre><code>from sqlalchemy import event from sqlalchemy import DDL event.listen( Article.__table__, "after_create", DDL("DBCC checkident (%(table)s, reseed, 9999)") ) </code></pre> <p>This will make the next record inserted start at an identity value of 10000. Good luck.</p>
0
2016-08-29T13:01:55Z
[ "python", "sql-server", "sqlalchemy", "pymssql" ]
I am trying to download data from Yahoo Finance using pandasb but nothing happens?
39,183,147
<pre><code>import pandas_datareader.data as web import datetime start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2013, 1, 27) f = web.DataReader("ugaz", 'yahoo', start, end) f.ix['2010-01-04'] </code></pre> <p>The above is the code I am currently trying to use to get data from Yahoo Finance. when I run the code I get this in the python shell 3.5.2 window</p> <pre><code>==================== RESTART: C:/Users/Zac/Desktop/ll.py ==================== </code></pre> <p>That's all that I get. I am using python 3.5 on windows 10 </p>
-1
2016-08-27T16:10:17Z
39,183,262
<p>The first datapoint is </p> <pre><code>f.ix['2012-02-08'] Open 48.360002 High 48.360002 Low 48.360002 Close 48.360002 Volume 0.000000 Adj Close 6045.000287 Name: 2012-02-08 00:00:00, dtype: float64 </code></pre>
0
2016-08-27T16:22:43Z
[ "python", "pandas", "yahoo-finance" ]
I am trying to download data from Yahoo Finance using pandasb but nothing happens?
39,183,147
<pre><code>import pandas_datareader.data as web import datetime start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2013, 1, 27) f = web.DataReader("ugaz", 'yahoo', start, end) f.ix['2010-01-04'] </code></pre> <p>The above is the code I am currently trying to use to get data from Yahoo Finance. when I run the code I get this in the python shell 3.5.2 window</p> <pre><code>==================== RESTART: C:/Users/Zac/Desktop/ll.py ==================== </code></pre> <p>That's all that I get. I am using python 3.5 on windows 10 </p>
-1
2016-08-27T16:10:17Z
39,274,713
<p>There are so many ways to download financial data, or any kind of data, from the web. The script below downloads stock prices and saves everything to a CSV file.</p> <pre><code>import urllib2 listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"] urls = [] for company in listOfStocks: urls.append('http://real-chart.finance.yahoo.com/table.csv?s=' + company + '&amp;d=6&amp;e=28&amp;f=2015&amp;g=m&amp;a=11&amp;b=12&amp;c=1980&amp;ignore=.csv') Output_File = open('C:/Users/your_path/Historical_Prices.csv','w') New_Format_Data = '' for counter in range(0, len(urls)): Original_Data = urllib2.urlopen(urls[counter]).read() if counter == 0: New_Format_Data = "Company," + urllib2.urlopen(urls[counter]).readline() rows = Original_Data.splitlines(1) for row in range(1, len(rows)): New_Format_Data = New_Format_Data + listOfStocks[counter] + ',' + rows[row] Output_File.write(New_Format_Data) Output_File.close() </code></pre> <p>The script below will download multiple stock tickers into one folder.</p> <pre><code>import urllib import re import json symbolslist = open("C:/Users/rshuell001/Desktop/symbols/tickers.txt").read() symbolslist = symbolslist.split("\n") for symbol in symbolslist: myfile = open("C:/Users/your_path/Desktop/symbols/" +symbol +".txt", "w+") myfile.close() htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+ symbol+ ":US") data = json.load(htmltext) datapoints = data["data_values"] myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "a") for point in datapoints: myfile.write(str(symbol+","+str(point[0])+","+str(point[1])+"\n")) myfile.close() </code></pre> <p>Finally...this will download prices for multiple stock tickers...</p> <pre><code>import urllib import re symbolfile = open("C:/Users/your_path/Desktop/symbols/amex.txt") symbollist = symbolfile.read() newsymbolslist = symbollist.split("\n") i=0 while i&lt;len(newsymbolslist): url = "http://finance.yahoo.com/q?s=" + newsymbolslist[i] + "&amp;ql=1" htmlfile = urllib.urlopen(url) htmltext = htmlfile.read() regex = '&lt;span id="yfs_l84_' + newsymbolslist[i] + '"&gt;(.+?)&lt;/span&gt;' pattern = re.compile(regex) price = re.findall(pattern,htmltext) print "the price of ", newsymbolslist[i] , "is", price[0] i+=1 # Make sure you place the 'amex.txt' file in 'C:\Python27\' </code></pre> <p>I wrote a book about these kinds of things, and lots of other stuff. You can find it using the URL below.</p> <p><a href="http://rads.stackoverflow.com/amzn/click/B01DJJKVZC" rel="nofollow">https://www.amazon.com/Automating-Business-Processes-Reducing-Increasing-ebook/dp/B01DJJKVZC/ref=sr_1_1</a>?</p>
0
2016-09-01T14:48:56Z
[ "python", "pandas", "yahoo-finance" ]
Django with HTML Forms
39,183,155
<p>I know how to set up Django forms to have Django render them. Unfortunately styling forms then becomes a little less straight forward. I am interested in finding a way to have the HTML form pass its entered values to Django. The HTML form is completely programmed in HTML and CSS. Just for context, please find below a list of solutions I dismissed for several reasons:</p> <ul> <li>Set up custom template filter (<a href="http://stackoverflow.com/questions/5827590/css-styling-in-django-forms">CSS styling in Django forms</a>)</li> <li>Use a for loop in order to loop through each form and render each field in turn (<a href="http://stackoverflow.com/questions/18805999/how-to-style-a-django-form-bootstrap">How to style a django form - bootstrap</a>)</li> <li>Reference the form fields directly y using list items <a href="http://stackoverflow.com/posts/5930179/revisions">http://stackoverflow.com/posts/5930179/revisions</a></li> </ul> <p>My problem with the first two solutions is that my s inside my form rely on class attributes which sees them assigned into a left or right column (col_half and col_half col_last). </p> <p>The third doesn't quite work for me since my form is not using list items. If I happen to convert my form into list items, a strange border is added into the form field (see screenshot below). </p> <p>As such I am wondering whether there is a way to just keep my HTML template and assign its valued to the forms.py one-by-one without getting this strange border (ideally I would like to stick to my input tag)? Any ad advice would be highly appreciated.</p> <p>Please see the HTML form below:</p> <p><a href="http://i.stack.imgur.com/5x3Ck.png" rel="nofollow"><img src="http://i.stack.imgur.com/5x3Ck.png" alt="strange border in First Name field"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="register-form" name="register-form" class="nobottommargin" action="#" method="post"&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-name"&gt;First Name:&lt;/label&gt; &lt;input type="text" id="register-form-name" name="register-form-name" value="" class="form-control"/&gt; &lt;/div&gt; &lt;div class="col_half col_last"&gt; &lt;label for="register-form-name"&gt;Last Name:&lt;/label&gt; &lt;input type="text" id="register-form-name" name="register-form-name" value="" class="form-control" /&gt; &lt;/div&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-email"&gt;Email Address:&lt;/label&gt; &lt;input type="text" id="register-form-email" name="register-form-email" value="" class="form-control" /&gt; &lt;/div&gt; &lt;!-- &lt;div class="clear"&gt;&lt;/div&gt; --&gt; &lt;div class="col_half col_last"&gt; &lt;label for="register-form-username"&gt;Choose a Username:&lt;/label&gt; &lt;input type="text" id="register-form-username" name="register-form-username" value="" class="form-control" /&gt; &lt;/div&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-phone"&gt;Phone:&lt;/label&gt; &lt;input type="text" id="register-form-phone" name="register-form-phone" value="" class="form-control" /&gt; &lt;/div&gt; &lt;!--&lt;div class="clear"&gt;&lt;/div&gt; --&gt; &lt;div class="col_half col_last"&gt; &lt;label for="register-form-phone"&gt;Country&lt;/label&gt; &lt;input type="text" id="register-form-phone" name="register-form-phone" value="" class="form-control" /&gt; &lt;/div&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-password"&gt;Choose Password:&lt;/label&gt; &lt;input type="password" id="register-form-password" name="register-form-password" value="" class="form-control" /&gt; &lt;/div&gt; &lt;div class="col_half col_last"&gt; &lt;label for="register-form-repassword"&gt;Re-enter Password:&lt;/label&gt; &lt;input type="password" id="register-form-repassword" name="register-form-repassword" value="" class="form-control" /&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;div class="col_full nobottommargin"&gt; &lt;button class="button button-3d button-black nomargin" id="register-form-submit" name="register-form-submit" value="register"&gt;Register Now&lt;/button&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
0
2016-08-27T16:10:49Z
39,183,460
<p>Ok, I figured it out. </p> <p>The trick was to realize that Django will already render its form tags (i.e. {{form.firstName}}) to an input tag. We can then add class attributes to this tag in in forms.py where we define this form:</p> <p><strong>HTML:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="register-form" name="register-form" class="nobottommargin" action="#" method="post"&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-name"&gt;First Name:&lt;/label&gt; {{ form.firstName }} &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p><strong>FORMS.PY:</strong></p> <pre><code>class newUserRegistration(forms.Form): firstName = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id':'register-form-name', 'name':'register-form-name', 'value':"", 'class':'form-control'})) </code></pre> <p><strong>THIS RENDERS THE HTML AS FOLLOWS</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="register-form" name="register-form" class="nobottommargin" action="#" method="post"&gt; &lt;div class="col_half"&gt; &lt;label for="register-form-name"&gt;First Name:&lt;/label&gt; &lt;input type="text" id="register-form-name" name="register-form-name" value="" class="form-control" /&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>By adding the attributes to forms.py we are essentially rendering the input tag into the HTML.</p>
0
2016-08-27T16:43:21Z
[ "python", "html", "css", "django" ]
remove the screen in back of the Tkinter message box
39,183,177
<p>I want to show a message box, but without the parent window behind it in Python. This is my code:</p> <pre><code>import Tkinter, tkFileDialog ,tkMessageBox from fileManagerModule import fileManager def load(): global myFile,flag,msg flag=True options = {} options["title"] = "choose a text File" options['initialdir'] = '~/' fileName = tkFileDialog.askopenfilename(**options) myFile = fileManager(fileName) myText.delete("1.0", Tkinter.END) try: line = myFile.readFromFile() myText.insert("1.0", line) except: msg=Tkinter.Tk() msg=tkMessageBox.showerror("Error","please choose file to load") </code></pre> <p><a href="http://i.stack.imgur.com/f4iv9.png" rel="nofollow">screenshot</a></p>
-1
2016-08-27T16:13:10Z
39,183,779
<p>You can use the <code>withdraw()</code> function to remove the <code>window</code> being displayed in the background to just show the dialog box only.</p> <p><strong>try this:</strong></p> <pre><code>import Tkinter, tkFileDialog ,tkMessageBox from fileManagerModule import fileManager def load(): global myFile,flag,msg flag=True options = {} options["title"] = "choose a text File" options['initialdir'] = '~/' fileName = tkFileDialog.askopenfilename(**options) myFile = fileManager(fileName) myText.delete("1.0", Tkinter.END) try: line = myFile.readFromFile() myText.insert("1.0", line) except: msg=Tkinter.Tk() msg.withdraw() msg=tkMessageBox.showerror("Error","please choose file to load") </code></pre>
1
2016-08-27T17:17:56Z
[ "python", "python-2.7", "tkinter" ]
C++ OOP: how to create a random number generator object?
39,183,275
<p>So this question is sort of one of translation. I am new to C++, and was looking through the class documentation. However, it looks like finding the answer to my question is a bit hard via the documentation. </p> <p>I have code for generating a random number between 0 and 1 in C++: (obtained from <a href="http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution" rel="nofollow">here</a>, since the rand() function solution for floats is integer based)</p> <pre><code>#include &lt;random&gt; #include &lt;iostream&gt; int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution&lt;&gt; dis(0, 1); //corrected from 1,2 for (int n = 0; n &lt; 10; ++n) { std::cout &lt;&lt; dis(gen) &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } </code></pre> <p>Next, I would like to create a class or struct or something (not really an OOP guy) that has an API like: </p> <pre><code>float x = my_RandomNumberGenerator.next(); </code></pre> <p>In python, I might write something like: </p> <pre><code>class my_RNG(): def __init__(self): self.rd = (the random device object I initialize in c code) self.gen = (the mersenne_twister engine object)(rd) self.distribution = (the uniform real distribution object) def next(): return self.distribution(self.gen) my_randomNumberGenerator = my_RNG() print(my_randomNumberGenerator.next()) </code></pre> <p>How would I implement this in C++? </p> <p><strong>update</strong> Here is what I have so far (it does not work... or compile...but there seems to be some strangeness in the way things are initialized in my template code that I got from the reference site that I don't understand): </p> <pre><code>#include &lt;iostream&gt; #include &lt;random&gt; class MyRNG { public: float next(void); private: std::random_device randomDevice; std::mt19937_64 randomGenerator; std::uniform_real_distribution distribution; MyRNG(float range_lower,float range_upper); }; MyRNG::MyRNG(float range_lower, float range_upper) { randomGenerator = std::mersenne_twister_engine(randomDevice); distribution = std::uniform_real_distribution&lt;&gt; distribution(range_lower,range_upper); } MyRNG::next(void) { return distribution(randomGenerator); } int main() { MyRNG my_rng = MyRNG(0,1); std::cout &lt;&lt; my_rng.next() &lt;&lt; std::endl; return 0; } </code></pre>
-1
2016-08-27T16:24:00Z
39,183,348
<p>You can create a class that holds a random number generator as a private member variable (like <code>std::mt19937</code>) and seeds it in the constructor. Your <code>next</code> function could just invoke the stored generator to get the next value (applying whatever distribution you want (if any) of course).</p> <p>This is not very complicated, so I'm afraid I'm missing the <em>real</em> point of your question..</p>
2
2016-08-27T16:31:16Z
[ "python", "c++", "oop" ]
C++ OOP: how to create a random number generator object?
39,183,275
<p>So this question is sort of one of translation. I am new to C++, and was looking through the class documentation. However, it looks like finding the answer to my question is a bit hard via the documentation. </p> <p>I have code for generating a random number between 0 and 1 in C++: (obtained from <a href="http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution" rel="nofollow">here</a>, since the rand() function solution for floats is integer based)</p> <pre><code>#include &lt;random&gt; #include &lt;iostream&gt; int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution&lt;&gt; dis(0, 1); //corrected from 1,2 for (int n = 0; n &lt; 10; ++n) { std::cout &lt;&lt; dis(gen) &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } </code></pre> <p>Next, I would like to create a class or struct or something (not really an OOP guy) that has an API like: </p> <pre><code>float x = my_RandomNumberGenerator.next(); </code></pre> <p>In python, I might write something like: </p> <pre><code>class my_RNG(): def __init__(self): self.rd = (the random device object I initialize in c code) self.gen = (the mersenne_twister engine object)(rd) self.distribution = (the uniform real distribution object) def next(): return self.distribution(self.gen) my_randomNumberGenerator = my_RNG() print(my_randomNumberGenerator.next()) </code></pre> <p>How would I implement this in C++? </p> <p><strong>update</strong> Here is what I have so far (it does not work... or compile...but there seems to be some strangeness in the way things are initialized in my template code that I got from the reference site that I don't understand): </p> <pre><code>#include &lt;iostream&gt; #include &lt;random&gt; class MyRNG { public: float next(void); private: std::random_device randomDevice; std::mt19937_64 randomGenerator; std::uniform_real_distribution distribution; MyRNG(float range_lower,float range_upper); }; MyRNG::MyRNG(float range_lower, float range_upper) { randomGenerator = std::mersenne_twister_engine(randomDevice); distribution = std::uniform_real_distribution&lt;&gt; distribution(range_lower,range_upper); } MyRNG::next(void) { return distribution(randomGenerator); } int main() { MyRNG my_rng = MyRNG(0,1); std::cout &lt;&lt; my_rng.next() &lt;&lt; std::endl; return 0; } </code></pre>
-1
2016-08-27T16:24:00Z
39,183,450
<p>Seems like you just need some form of probability generation class, see below for a basic implementation which meets your question requirements:</p> <pre><code>template&lt;class Ty = double, class = std::enable_if_t&lt;std::is_floating_point&lt;Ty&gt;::value&gt; &gt; class random_probability_generator { public: // default constructor uses single random_device for seeding random_probability_generator() : mt_eng{std::random_device{}()}, prob_dist(0.0, 1.0) {} // ... other constructors with custom seeds if necessary Ty next() { return prob_dist(mt_eng); } // ... other methods if necessary private: std::mt19937 mt_eng; std::uniform_real_distribution&lt;Ty&gt; prob_dist; }; </code></pre> <p>Then you can use this simply via:</p> <pre><code>random_probability_generator&lt;&gt; pgen; double p = pgen.next(); // double in range [0.0, 1.0] </code></pre> <p>Or if you want random <code>float</code>s instead (as part of your question seems to imply):</p> <pre><code>random_probability_generator&lt;float&gt; pgen; float p = pgen.next(); // float in range [0.0f, 1.0f] </code></pre> <hr> <p>Also, to address why the class you posted isn't compiling, the error in your class is that you try to initialise a <code>std::mt19937_64</code> type object (<code>randomGenerator</code>) with a <code>std::mersenne_twister_engine</code> instance but they are fundamentally different types. Instead you would need to do </p> <pre><code>randomGenerator = std::mt19937_64(randomDevice()); </code></pre> <p>in <code>MyRNG</code> constructor, or construct via initialisation list as I have done in the example above. </p> <hr> <p>As pointed out in the comments, a more suitable <em>c++-esque</em> implementation of this is to overload <code>operator()</code> instead of creating a <code>next()</code> method. See below for a better implementation of the above class,</p> <pre><code>template&lt;class FloatType = double, class Generator = std::mt19937, class = std::enable_if_t&lt;std::is_floating_point&lt;FloatType&gt;::value&gt; &gt; class uniform_random_probability_generator { public: typedef FloatType result_type; typedef Generator generator_type; typedef std::uniform_real_distribution&lt;FloatType&gt; distribution_type; // default constructor explicit uniform_random_probability_generator(Generator&amp;&amp; _eng = Generator{std::random_device{}()}) : eng(std::move(_eng)), dist() {} // construct from existing pre-defined engine explicit uniform_random_probability_generator(const Generator&amp; _eng) : eng(_eng), dist() {} // generate next random value in distribution (equivalent to next() in above code) result_type operator()() { return dist(eng); } // will always yield 0.0 for this class type constexpr result_type min() const { return dist.min(); } // will always yield 1.0 for this class type constexpr result_type max() const { return dist.max(); } // resets internal state such that next call to operator() // does not rely on previous call void reset_distribution_state() { dist.reset(); } private: generator_type eng; distribution_type dist; }; </code></pre> <p>Then you can use this similarly to the first class in this answer,</p> <pre><code>uniform_random_probability_generator&lt;&gt; urpg; double next_prob = urpg(); </code></pre> <p>Additionally, <code>uniform_random_probability_generator</code> can use a different <code>Generator</code> type as a template parameter so long as this type meets the requirements of <a href="http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator" rel="nofollow"><code>UniformRandomBitGenerator</code></a>. For example, if for any reason you needed to use <code>std::knuth_b</code> instead of <code>std::mt19937</code> then you can do so as follows:</p> <pre><code>uniform_random_probability_generator&lt;double, std::knuth_b&gt; urpg_kb; double next_prob = urpg_kb(); </code></pre>
3
2016-08-27T16:42:29Z
[ "python", "c++", "oop" ]
I get the error, list indices must be integers, do not know why?
39,183,310
<pre><code>for i in inpt: for j in inpt[i]: print j, </code></pre> <p>I want to access a 2D array, for each array i in inpt, I want to print each number j in the array i. I do not have any formal background in python and also I could not already find a solution on the internet.</p>
0
2016-08-27T16:27:33Z
39,183,324
<p>Python <code>for</code> loops are <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> loops</a>, in that you get the actual elements from the list and not an index. You are trying to use those elements as indices to <code>inpt</code> again.</p> <p>Loop over <code>i</code>, not <code>inpt[i]</code>, to get the matrix values:</p> <pre><code>for i in inpt: for j in i: print j, </code></pre> <p>I'd rename <code>i</code> to <code>row</code> to make this clearer:</p> <pre><code>for row in inpt: for j in row: print j, </code></pre>
1
2016-08-27T16:28:54Z
[ "python", "python-2.7" ]
Finding anchor tags within a table using selenium chromedriver
39,183,383
<p>I am trying to build an application that automates the process of downloading several anime episodes and i am stuck. So far i've been able to locate the episode links using the following code:</p> <pre><code>def get_episodes(driver): WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[contains(@title,'Episode')]"))) episodes = driver.find_elements_by_xpath("//a[contains(@title,'Episode')]") del episodes[-1] episodes = list(reversed(episodes)) return episodes </code></pre> <p>However recently i've found out that not every episode contains the word 'episode' in its link text. As such, i am trying to figure out another way to get every link to an episode. The basic structure of the page contains a table, and each link is located inside a <code>&lt;td&gt;</code> element.</p> <p>I've thought of gathering all the td elements, and then getting their children (or should i say child) by using css selectors. Nevertheless, this won't work either because there are more <code>&lt;td&gt;</code> elements than those that meet the eye.</p> <p>Here's an <a href="http://kissanime.to/Anime/Death-Note-Dub" rel="nofollow">example page</a> for reference. I am a noob as far as selenium is concerned, and thus not very familiar with its api, so i don't know exactly what i am looking for. Any suggestion is appreciated.</p>
2
2016-08-27T16:34:46Z
39,183,490
<p>Try to make your <code>XPath</code> more specific:</p> <pre><code>//tr/td/a[starts-with(@href,'/Anime/')] </code></pre>
1
2016-08-27T16:46:24Z
[ "python", "selenium", "selenium-chromedriver" ]
Finding anchor tags within a table using selenium chromedriver
39,183,383
<p>I am trying to build an application that automates the process of downloading several anime episodes and i am stuck. So far i've been able to locate the episode links using the following code:</p> <pre><code>def get_episodes(driver): WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[contains(@title,'Episode')]"))) episodes = driver.find_elements_by_xpath("//a[contains(@title,'Episode')]") del episodes[-1] episodes = list(reversed(episodes)) return episodes </code></pre> <p>However recently i've found out that not every episode contains the word 'episode' in its link text. As such, i am trying to figure out another way to get every link to an episode. The basic structure of the page contains a table, and each link is located inside a <code>&lt;td&gt;</code> element.</p> <p>I've thought of gathering all the td elements, and then getting their children (or should i say child) by using css selectors. Nevertheless, this won't work either because there are more <code>&lt;td&gt;</code> elements than those that meet the eye.</p> <p>Here's an <a href="http://kissanime.to/Anime/Death-Note-Dub" rel="nofollow">example page</a> for reference. I am a noob as far as selenium is concerned, and thus not very familiar with its api, so i don't know exactly what i am looking for. Any suggestion is appreciated.</p>
2
2016-08-27T16:34:46Z
39,183,508
<p>You're on the right track, but you may be over-thinking this a bit. Why not just target the table that we know has the episodes, then use a list comprehension to grab all the episode links?</p> <pre><code>def get_episodes(): episode_table = driver.find_element_by_class_name('listing') episode_links = [i.get_attribute('href') for i in episode_table.find_elements_by_tag_name('a')] print(episode_links) &gt;&gt;&gt;['http://kissanime.to/Anime/Death-Note-Dub/Episode-037?id=97557', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-036?id=97556', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-035?id=97555', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-034?id=97554',etc..] </code></pre>
0
2016-08-27T16:48:17Z
[ "python", "selenium", "selenium-chromedriver" ]
Python Save a (Sparse) Matrix with a variable inside
39,183,417
<p>I have some matrices of decent size (2000*2000) and I wish to have symbolic expressions in the elements of the matrices - i.e. <code>.9**b + .8**b + .7**b ...</code> is an example of an element. The matrices are quite sparse.</p> <p>I am creating these matrices by adding up intermediate calculations. I would like to store them to disk to be read in later and evaluated with different values of <code>b</code>.</p> <p>I have played around with sympy and it does exactly what I need it to do however it is mind-numbingly slow to do simple additions. From what I have read it seems theano or tensorflow might be able to do this with Tensors but I could not figure out how to put a symbol in a Tensor.</p> <p>Can anyone point me in the right direction as to the best tool to use for this task? I'd prefer it to be in python but if something outside python would do the job that'd be nice too.</p>
6
2016-08-27T16:38:11Z
39,214,491
<p>The problem is likely coming from the fact that you are taking a symbolic power. But, for whatever reason, SymPy tries to find an explicit form for a symbolic power. For example:</p> <pre><code>In [12]: x = Symbol('x') In [13]: print(Matrix([[1, 2], [3, 4]])**x) Matrix([[-2*(5/2 + sqrt(33)/2)**x*(-2/((-3/2 + sqrt(33)/2)*(-1/2 + sqrt(33)/6)**2*(sqrt(33)/4 + 11/4)) + 1/(-1/2 + sqrt(33)/6))/(-sqrt(33)/2 - 3/2) + 2*(-sqrt(33)/2 + 5/2)**x/((-3/2 + sqrt(33)/2)*(-1/2 + sqrt(33)/6)*(sqrt(33)/4 + 11/4)), -4*(5/2 + sqrt(33)/2)**x/((-3/2 + sqrt(33)/2)*(-1/2 + sqrt(33)/6)*(-sqrt(33)/2 - 3/2)*(sqrt(33)/4 + 11/4)) - 2*(-sqrt(33)/2 + 5/2)**x/((-3/2 + sqrt(33)/2)*(sqrt(33)/4 + 11/4))], [(5/2 + sqrt(33)/2)**x*(-2/((-3/2 + sqrt(33)/2)*(-1/2 + sqrt(33)/6)**2*(sqrt(33)/4 + 11/4)) + 1/(-1/2 + sqrt(33)/6)) - (-sqrt(33)/2 + 5/2)**x/((-1/2 + sqrt(33)/6)*(sqrt(33)/4 + 11/4)), 2*(5/2 + sqrt(33)/2)**x/((-3/2 + sqrt(33)/2)*(-1/2 + sqrt(33)/6)*(sqrt(33)/4 + 11/4)) + (-sqrt(33)/2 + 5/2)**x/(sqrt(33)/4 + 11/4)]]) </code></pre> <p>Is this actually what you want to do? Do you know the value of <code>b</code> ahead of time? You can leave the expression unevaluated as a power by using <code>MatPow(arr, b)</code>. </p>
0
2016-08-29T20:16:49Z
[ "python", "sympy", "symbolic-math" ]
Write multiple Numpy arrays of different dtype as columns of CSV file
39,183,471
<p>What would be the best way to write multiple numpy arrays of different dtype as different columns of a single CSV file?</p> <p>For instance, given the following arrays:</p> <pre><code>array([[1, 2], [3, 4], [5, 6]]) array([[ 10., 20.], [ 30., 40.], [ 50., 60.]]) </code></pre> <p>I would like to obtain a file (delimiter irrelevant):</p> <pre><code>1 2 10.0 20.0 3 4 30.0 40.0 5 6 50.0 60.0 </code></pre> <p>Optimally, I would like to be able to write a list of arrays this way, where a format/dtype can be different for every array.</p> <p>I tried looking at <code>savetxt</code>, but it's not clear to me how to use it if the arrays have a different type.</p>
2
2016-08-27T16:44:30Z
39,183,525
<p>use <code>np.concatenate</code> in order to concatenate the arrays along the second axis then use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt" rel="nofollow"><code>np.savetxt</code></a> inorder to save your array in a a text format.</p> <pre><code>import numpy as np a = np.array([[1, 2], [3, 4], [5, 6]]) b = np. array([[10., 20.], [30., 40.], [50., 60.]]) np.savetxt('filename.csv', np.concatenate((a,b), axis=1)) </code></pre> <p>Note that <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt" rel="nofollow"><code>np.savetxt</code></a> also accepts another arguments like <code>delimiter</code>.</p> <blockquote> <p><code>numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')</code></p> </blockquote>
1
2016-08-27T16:50:41Z
[ "python", "csv", "numpy" ]
Write multiple Numpy arrays of different dtype as columns of CSV file
39,183,471
<p>What would be the best way to write multiple numpy arrays of different dtype as different columns of a single CSV file?</p> <p>For instance, given the following arrays:</p> <pre><code>array([[1, 2], [3, 4], [5, 6]]) array([[ 10., 20.], [ 30., 40.], [ 50., 60.]]) </code></pre> <p>I would like to obtain a file (delimiter irrelevant):</p> <pre><code>1 2 10.0 20.0 3 4 30.0 40.0 5 6 50.0 60.0 </code></pre> <p>Optimally, I would like to be able to write a list of arrays this way, where a format/dtype can be different for every array.</p> <p>I tried looking at <code>savetxt</code>, but it's not clear to me how to use it if the arrays have a different type.</p>
2
2016-08-27T16:44:30Z
39,184,228
<pre><code>In [38]: a=np.arange(1,7).reshape(3,2) In [39]: b=np.arange(10,70.,10).reshape(3,2) In [40]: c=np.concatenate((a,b),axis=1) In [41]: c Out[41]: array([[ 1., 2., 10., 20.], [ 3., 4., 30., 40.], [ 5., 6., 50., 60.]]) </code></pre> <p>All values are float; default <code>savetxt</code> is a general float:</p> <pre><code>In [43]: np.savetxt('test.csv',c) In [44]: cat test.csv 1.000000000000000000e+00 2.000000000000000000e+00 1.000000000000000000e+01 2.000000000000000000e+01 3.000000000000000000e+00 4.000000000000000000e+00 3.000000000000000000e+01 4.000000000000000000e+01 5.000000000000000000e+00 6.000000000000000000e+00 5.000000000000000000e+01 6.000000000000000000e+01 </code></pre> <p>With a custom <code>fmt</code> I can get:</p> <pre><code>In [46]: np.savetxt('test.csv',c,fmt='%2d %2d %5.1f %5.1f') In [47]: cat test.csv 1 2 10.0 20.0 3 4 30.0 40.0 5 6 50.0 60.0 </code></pre> <p>More generally we can make a <code>c</code> with a compound dtype. It isn't needed here with just floats and ints, but with strings it would matter. But we still need a long <code>fmt</code> to display the columns correctly.</p> <p><code>np.rec.fromarrays</code> is an easy way to generate a structured arrays. Unfortunately it only works with flattened arrays. So for your (3,2) arrays I need to list the columns separately.</p> <pre><code>In [52]: c = np.rec.fromarrays((a[:,0],a[:,1],b[:,0],b[:,1])) In [53]: c Out[53]: rec.array([(1, 2, 10.0, 20.0), (3, 4, 30.0, 40.0), (5, 6, 50.0, 60.0)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4'), ('f2', '&lt;f8'), ('f3', '&lt;f8')]) In [54]: np.savetxt('test.csv',c,fmt='%2d %2d %5.1f %5.1f') In [55]: cat test.csv 1 2 10.0 20.0 3 4 30.0 40.0 5 6 50.0 60.0 </code></pre> <p>I'm using the same <code>savetxt</code>.</p> <p>I could also make a structured array with 2 fields, each being 2 columns. I'm not sure if <code>savetxt</code> would work with that or not.</p> <p><code>savetxt</code> essentially iterates over the 1st dimension of your array, and does a formatted write on each row, roughly:</p> <pre><code>for row in arr: f.write(fmt%tuple(row)) </code></pre> <p>where <code>fmt</code> is derived from your parameter.</p> <p>It wouldn't be hard to write your own version that iterates on 2 arrays, and does a separate formatted write for each pair of rows.</p> <pre><code>for r1,r2 in zip(a,b): print('%2d %2d'%tuple(r1), '%5.1f %5.1f'%tuple(r2)) </code></pre> <p>===================</p> <p>Trying a compound dtype</p> <pre><code>In [60]: np.dtype('2i,2f') Out[60]: dtype([('f0', '&lt;i4', (2,)), ('f1', '&lt;f4', (2,))]) In [61]: c=np.zeros(a.shape[0], np.dtype('2i,2f')) In [62]: c['f0']=a In [63]: c['f1']=b In [64]: c Out[64]: array([([1, 2], [10.0, 20.0]), ([3, 4], [30.0, 40.0]), ([5, 6], [50.0, 60.0])], dtype=[('f0', '&lt;i4', (2,)), ('f1', '&lt;f4', (2,))]) In [65]: np.savetxt('test.csv',c,fmt='%2d %2d %5.1f %5.1f') --- ValueError: fmt has wrong number of % formats: %2d %2d %5.1f %5.1f </code></pre> <p>So writing a compound dtype like this does not work. Considering that a row of <code>c</code> looks like:</p> <pre><code>In [69]: tuple(c[0]) Out[69]: (array([1, 2], dtype=int32), array([ 10., 20.], dtype=float32)) </code></pre> <p>I shouldn't be surprised.</p> <p>I can save the two blocks with <code>%s</code> format, but that leaves me with brackets.</p> <pre><code>In [66]: np.savetxt('test.csv',c,fmt='%s %s') In [67]: cat test.csv [1 2] [ 10. 20.] [3 4] [ 30. 40.] [5 6] [ 50. 60.] </code></pre> <p>I think there is a <code>np.rec</code> function that flattens the dtype. But I can also do that with a <code>view</code>:</p> <pre><code>In [72]: np.savetxt('test.csv',c.view('i,i,f,f'),fmt='%2d %2d %5.1f %5.1f') In [73]: cat test.csv 1 2 10.0 20.0 3 4 30.0 40.0 5 6 50.0 60.0 </code></pre> <p>So as long as you are dealing with numeric values, the simple concatenate is just as good as the more complex structured approaches.</p> <p>============</p>
1
2016-08-27T18:06:54Z
[ "python", "csv", "numpy" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r".*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>Another question building up on the previous exercise: I need to add a new alternative condition i.e. that the words starts with 1 and only 1 capital letter.</p> <p>I wrote</p> <pre><code>L2=[w for w in text6 if re.search(r"[A-Z]{1}|.*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>It includes also upper case words (i.e all characters in capital letter)</p> <p>Could any one help in these 2 questions?</p> <p>Thank you in advance</p> <p>mauro</p>
3
2016-08-27T16:51:51Z
39,183,627
<p>You are iterating over the characters not the words, for that case you need to split your text.</p> <p>Also you can do all of these jobs without regex:</p> <pre><code>from string import ascii_uppercase def check_word(word): return 'z' in word or 'pt' in word or word.endswith('ize') or word.startswith(tuple(ascii_uppercase)) [w for w in text6.split() if check_word(w)] </code></pre> <p>Demo :</p> <pre><code>&gt;&gt;&gt; text6 = "here are some example: appease dance offensive xxxize executive and other extra words optimum Python" &gt;&gt;&gt; [w for w in text6.split() if check_word(w)] ['xxxize', 'optimum', 'Python'] </code></pre> <p>For the last condition (<em>the words starts with 1 and only 1 capital letter</em>) if you don't want any upper case in word except the first one you can add (<code>word[1:].islower()</code>) to <code>check_word</code> function:</p> <pre><code>def check_word(word): return 'z' in word or 'pt' in word or word.endswith('ize') or (word.startswith(tuple(ascii_uppercase)) and word[1:].islower()) </code></pre> <p><em>Note</em>: If you want to separate the words with multiple delimiter or based on another condition you can use <code>re.findall()</code> in order to find the words.</p> <p>For example the following regex will wind the words contain word characters:</p> <pre><code>re.findall(r'\b\w+\b', my_str) </code></pre>
2
2016-08-27T17:00:58Z
[ "python", "regex" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r".*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>Another question building up on the previous exercise: I need to add a new alternative condition i.e. that the words starts with 1 and only 1 capital letter.</p> <p>I wrote</p> <pre><code>L2=[w for w in text6 if re.search(r"[A-Z]{1}|.*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>It includes also upper case words (i.e all characters in capital letter)</p> <p>Could any one help in these 2 questions?</p> <p>Thank you in advance</p> <p>mauro</p>
3
2016-08-27T16:51:51Z
39,183,657
<p>What you are looking for is:</p> <pre><code>[w for w in text6 if re.search(r"z|pt|ize$", w)] </code></pre> <p>This will capture all the required words. Note that, the last part is not required as any word matching <code>ize$</code> will also match <code>z</code>. So essentially, the expression boils down to:</p> <pre><code>[w for w in text6 if re.search(r"z|pt", w)] </code></pre> <p>The second case can be solved by using the expression <code>^[A-Z]{1}[^A-Z]</code>. That is,</p> <ul> <li>Starts with exactly one capital letter</li> <li>Isn't followed by a capital letter</li> </ul> <p>This is used below:</p> <pre><code>[w for w in text6 if re.search(r"^[A-Z]{1}[^A-Z]|z|pt|ize$", w)] </code></pre> <p>Or, simply,</p> <pre><code>[w for w in text6 if re.search(r"^[A-Z]{1}[^A-Z]|z|pt", w)] </code></pre>
1
2016-08-27T17:04:24Z
[ "python", "regex" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r".*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>Another question building up on the previous exercise: I need to add a new alternative condition i.e. that the words starts with 1 and only 1 capital letter.</p> <p>I wrote</p> <pre><code>L2=[w for w in text6 if re.search(r"[A-Z]{1}|.*[z]|.*[p][t]|[ize]$",w) </code></pre> <p>It includes also upper case words (i.e all characters in capital letter)</p> <p>Could any one help in these 2 questions?</p> <p>Thank you in advance</p> <p>mauro</p>
3
2016-08-27T16:51:51Z
39,183,736
<p>I would suggest a non-regex approach here, since regex seems more complicated than this use case demands.</p> <p>For one, you can get rid of the "ends in <code>ize</code>" constraint, because that falls under any words with <code>z</code> in it.</p> <pre><code>text6 = [ 'appease', 'dance', 'offensive', 'executive', 'inept', 'zoo', 'Inept', 'Zoo', 'INept', 'ZOo'] </code></pre> <p>For just matching words with lowercased <code>pt</code> or <code>z</code>:</p> <pre><code>[w for w in text6 if 'pt' in w or 'z' in w] # ['inept', 'zoo', 'Inept', 'INept'] </code></pre> <p>For matching the above cases as well as only capitalized words:</p> <pre><code>[w for w in text6 if w.istitle() and ('pt' in w or 'z' in w)] # ['Inept'] </code></pre> <p>Of course, it may be better to write a function that abstracts this logic out:</p> <pre><code>def meets_criteria(word): return word.istitle() and ('pt' in word or 'z' in word) [w for w in text6 if meets_criteria(w)] </code></pre> <p>If you want to also match words starting with <code>Z</code> and <code>Pt</code>, you can check membership in <code>w.lower()</code> instead.</p>
2
2016-08-27T17:13:52Z
[ "python", "regex" ]
How to take real time input output from a python script on PHP
39,183,586
<p>I want to take input from user through a html form, process it through a python script and print the output on html page. The problem is the whole python script is executed each time, while I want the script to give real time output for each input. How can I manage to do this ? </p> <p>Here is what I am doing so far.</p> <pre><code>&lt;?php $vout=''; if(isset($_POST['submit'])) { $vin=$_POST['input_text']; $vout=exec('python bot.py '.$vin); } ?&gt; &lt;form method="post"&gt; &lt;label&gt; BotIn: &lt;input type="text" name="input_text"&gt; &lt;/label&gt; &lt;input type="submit" name="submit"&gt; &lt;/form&gt; &lt;/br&gt;&lt;/br&gt; &lt;label&gt; &lt;p&gt;Bot: &lt;?=$vout?&gt;&lt;/p&gt; &lt;/label&gt; </code></pre>
0
2016-08-27T16:56:47Z
39,183,710
<p>The best way to solve your problem will be running simple python app using, let's say, <a href="http://flask.pocoo.org" rel="nofollow">Flask</a> and hit to specific endpoint you'll make in it. Everything then could take place through localhost, if you'll set it on the same machine.</p>
0
2016-08-27T17:10:25Z
[ "php", "python" ]
How `[System.Console]::OutputEncoding/InputEncoding` with Python?
39,183,614
<p>Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?</p> <pre class="lang-bsh prettyprint-override"><code>[system.console]::InputEncoding = [System.Text.Encoding]::UTF8; [system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; chcp; "import sys print(sys.stdout.encoding) print(sys.stdin.encoding) sys.stdout.write(sys.stdin.readline()) " | sc test.py -Encoding utf8; [char]0x0422+[char]0x0415+[char]0x0421+[char]0x0422+"`n" | py -3 test.py </code></pre> <p>prints:</p> <pre><code>Active code page: 65001 cp65001 cp1251 п»ї???? </code></pre>
15
2016-08-27T16:59:53Z
39,428,999
<p>You are piping data into Python; at that point Python's <code>stdin</code> is no longer attached to a TTY (your console) and won't guess at what the encoding might be. Instead, the default system locale is used; on your system that's cp1251 (the Windows Latin-1-based codepage).</p> <p>Set the <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING"><code>PYTHONIOENCODING</code> environment variable</a> to override:</p> <blockquote> <p><code>PYTHONIOENCODING</code><br> If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax <code>encodingname:errorhandler</code>. Both the <code>encodingname</code> and the <code>:errorhandler</code> parts are optional and have the same meaning as in <code>str.encode()</code>.</p> </blockquote> <p>PowerShell doesn't appear to support per-command-line environment variables the way UNIX shells do; the easiest is to just set the variable first:</p> <pre><code>Set-Item Env:PYTHONIOENCODING "UTF-8" </code></pre> <p>or even</p> <pre><code>Set-Item Env:PYTHONIOENCODING "cp65001" </code></pre> <p>as the Windows UTF-8 codepage is apparently not <em>quite</em> UTF-8 really, depending on the Windows version and on wether or not pipe redirection is used.</p>
8
2016-09-10T17:58:44Z
[ "python", ".net", "shell", "powershell" ]
How `[System.Console]::OutputEncoding/InputEncoding` with Python?
39,183,614
<p>Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?</p> <pre class="lang-bsh prettyprint-override"><code>[system.console]::InputEncoding = [System.Text.Encoding]::UTF8; [system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; chcp; "import sys print(sys.stdout.encoding) print(sys.stdin.encoding) sys.stdout.write(sys.stdin.readline()) " | sc test.py -Encoding utf8; [char]0x0422+[char]0x0415+[char]0x0421+[char]0x0422+"`n" | py -3 test.py </code></pre> <p>prints:</p> <pre><code>Active code page: 65001 cp65001 cp1251 п»ї???? </code></pre>
15
2016-08-27T16:59:53Z
39,543,595
<p>Why not embed CPython in powershell?! CPython is so easy to embed, and powershell is very good REPL to <a href="https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/creating-.net-and-com-objects--new-object-" rel="nofollow">play with .NET and COM objects</a>. Here is a simple introduction to using <a href="https://github.com/pythonnet/pythonnet" rel="nofollow">pythonnet</a> from PowerShell. Note how encoding is automatically propagated from powershell to python. </p> <pre><code>Windows PowerShell Copyright (C) 2015 Microsoft Corporation. All rights reserved. PS C:\Users\denfromufa&gt; [system.console]::InputEncoding = [System.Text.Encoding]::UTF8; PS C:\Users\denfromufa&gt; [system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; PS C:\Users\denfromufa&gt; [Reflection.Assembly]::LoadFile("C:\Python\Miniconda3_64b\Lib\site-packages\Python.Runtime.dll") GAC Version Location --- ------- -------- False v4.0.30319 C:\Python\Miniconda3_64b\Lib\site-packages\Python.Runtime.dll PS C:\Users\denfromufa&gt; $gil = [Python.Runtime.Py]::GIL() PS C:\Users\denfromufa&gt; $sys=[Python.Runtime.Py]::Import("sys") PS C:\Users\denfromufa&gt; $sys.stdin.encoding.ToString() cp65001 PS C:\Users\denfromufa&gt; $sys.stdout.encoding.ToString() cp65001 PS C:\Users\denfromufa&gt; $gil.Dispose() PS C:\Users\denfromufa&gt; [Python.Runtime.PythonEngine]::Shutdown() PS C:\Users\denfromufa&gt; </code></pre>
2
2016-09-17T06:32:51Z
[ "python", ".net", "shell", "powershell" ]
Understanding a memoization decorator as a closure
39,183,653
<p>I'm trying to learn about Python decorators, and I'd like to understand in more detail exactly how closure applies, for example in this memoization context:</p> <pre><code>def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper @memoize def fib(n): if n in (0,1): return n return fib(n - 1) + fib(n - 2) </code></pre> <p>I understand that <code>memoize</code> returns functions that are bound to <code>memo</code> values in the enclosing scope of <code>helper</code>, even when the program flow is no longer in that enclosing scope. So, if <code>memoize</code> is called repeatedly it will return a varying sequence of functions depending upon the current values of <code>memo</code>. I also understand that <code>@memoize</code> is syntactic sugar that causes calls to <code>fib(n)</code> to be replaced with calls to <code>memoize(fib(n))</code>.</p> <p>Where I am struggling is how the called value of <code>n</code> in <code>fib(n)</code> is effectively converted to the <code>x</code> in <code>helper(x)</code>. Most tutorials on closures don't seem to make this point explicit, or they rather vaguely say that one function ‘closes over’ the other, which just makes it sound like magic. I can see how to use the syntax, but would like to have a better grasp of exactly what is happening here and what objects and data are being passed around as the code executes.</p>
1
2016-08-27T17:03:55Z
39,183,776
<p>You've misunderstood what the <code>@memoize</code> decorator does. The decorator is not called each time you call <code>fib</code>. The decorator is called <em>just once</em> per function that is decorated.</p> <p>The original <code>fib</code> function is <em>replaced</em> by the <code>helper()</code> function, with the original function object available as the <code>f</code> closure, together with the <code>memo</code> closure:</p> <pre><code>&gt;&gt;&gt; def fib(n): ... if n in (0,1): ... return n ... return fib(n - 1) + fib(n - 2) ... &gt;&gt;&gt; fib &lt;function fib at 0x1023398c0&gt; &gt;&gt;&gt; memoize(fib) &lt;function helper at 0x102339758&gt; </code></pre> <p>This gives the replacement <code>helper</code> function <em>one</em> closure, and each time you call that <code>helper()</code> function the same <code>memo</code> dictionary is used to look up already-produced results for the current value of <code>x</code>.</p> <p>You can see this all work in the interpreter:</p> <pre><code>&gt;&gt;&gt; @memoize ... def fib(n): ... if n in (0,1): ... return n ... return fib(n - 1) + fib(n - 2) ... &gt;&gt;&gt; fib &lt;function helper at 0x10232ae60&gt; </code></pre> <p>Note the function name there! That's <code>helper</code>. It has a closure:</p> <pre><code>&gt;&gt;&gt; fib.__closure__ (&lt;cell at 0x10232d9f0: function object at 0x10232ade8&gt;, &lt;cell at 0x10232da98: dict object at 0x102353050&gt;) </code></pre> <p>A function object and a dictionary, those are <code>f</code> and <code>memo</code>, respectively. Access the cell contents with <code>.cell_contents</code>:</p> <pre><code>&gt;&gt;&gt; fib.__closure__[0].cell_contents &lt;function fib at 0x10232ade8&gt; &gt;&gt;&gt; fib.__closure__[1].cell_contents {} </code></pre> <p>That's the original decorated function and the empty dictionary alright. Let's use this function:</p> <pre><code>&gt;&gt;&gt; fib(0) 0 &gt;&gt;&gt; fib(1) 1 &gt;&gt;&gt; fib.__closure__[1].cell_contents {0: 0, 1: 1} </code></pre> <p>That's the resulting values for <code>x</code> set to <code>0</code> and <code>1</code> being stored in the <code>memo</code> dictionary. Next time I call <code>fib</code> with either value, the memo is used. New <code>x</code> values are calculated and added:</p> <pre><code>&gt;&gt;&gt; fib(2) 1 &gt;&gt;&gt; fib.__closure__[1].cell_contents {0: 0, 1: 1, 2: 1} </code></pre> <p>You can see how well that works by timing how long a larger number takes to calculate:</p> <pre><code>&gt;&gt;&gt; start = time.clock(); fib(500); print(format(time.clock() - start, '.10f')) 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125L 0.0008390000 &gt;&gt;&gt; start = time.clock(); fib(500); print(format(time.clock() - start, '.10f')) 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125L 0.0000220000 &gt;&gt;&gt; start = time.clock(); fib(500); print(format(time.clock() - start, '.10f')) 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125L 0.0000190000 </code></pre> <p>After the first call, looking up the memo is 40 times as fast as all the intermediate results have been memoized:</p> <pre><code>&gt;&gt;&gt; len(fib.__closure__[1].cell_contents) 501 </code></pre>
2
2016-08-27T17:17:31Z
[ "python", "closures", "memoization", "python-decorators" ]