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
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,336,875
<p>maybe oneliner : </p> <pre><code>s = map(lambda x : x*(x+1),list(range(1,20))) </code></pre> <p>basically <strong>map</strong> is core function used to make same operation on every element of table. first parameter is function which will be applied to every element. And If You want to remember generate another val...
0
2016-09-05T19:51:25Z
[ "python" ]
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,336,962
<p>Ok, I am not quite sure if I understand your question correctly, since you talk about modulus 11, but also seem to use numbers from 2 up to and including 9.</p> <p>But let's first start with writing the 1..20 as a list, that would be possible as follows:</p> <pre><code>list(range(1,21)) (This is if you want to ...
1
2016-09-05T19:58:33Z
[ "python" ]
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,336,991
<p>You don't have to worry about resetting the multiplier if you use <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a>:</p> <pre><code>&gt;&gt;&gt; itertools.cycle(range(2, 10)) 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, ... </code></pre> <p>so you can...
1
2016-09-05T20:00:32Z
[ "python" ]
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,337,007
<p>You can use the current index to determine the multiplier:</p> <pre><code>&gt;&gt;&gt; [(index % 8 + 2) * item for index, item in enumerate(range(1, 21))] [2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100] #^ resets ^ resets ^ </code></pre...
2
2016-09-05T20:01:38Z
[ "python" ]
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,337,134
<p>A lot of good answers here already, and in case you would like to use <code>numpy</code> (usually good for this sort of thing), here's an alternative:</p> <pre><code>In [1]: import numpy as np In [2]: a = np.arange(1, 21) # like range in numpy array In [3]: a - 1 # calculation performs per element wise... so w...
1
2016-09-05T20:13:31Z
[ "python" ]
Multiply number list by range of numbers
39,336,824
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p> <p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p> <p>Let's say I have a list of numbers <code>1..20</code> and I'd like to multiply them by <code...
4
2016-09-05T19:46:51Z
39,337,222
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.starmap" rel="nofollow">starmap</a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow">cycle</a> from itertools.</p> <p>First create a list of tuples to multiply together:</p> <pre><code>&gt;&...
1
2016-09-05T20:20:41Z
[ "python" ]
how to serve local static files in development when hosted in S3
39,336,973
<p>I'm storing my static files in S3 according to this tutorial: <a href="https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/" rel="nofollow">https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/</a></p>...
0
2016-09-05T19:59:18Z
39,337,686
<p>I set the following in my local_settings.py:</p> <pre><code>STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' </code></pre> <p>Then it looks for all static assets at localhost.</p>
0
2016-09-05T21:03:53Z
[ "javascript", "python", "django", "amazon-s3", "django-staticfiles" ]
Getting queue where task came from
39,336,983
<p>I have a Celery application with 2 queues in which tasks of a given class (say, MyTask) are consumed round-robin. Some instances of MyTask are routed to the first queue, while other instances go to the second one.</p> <p>Sometimes, a task needs to instantiate another object of MyTask and invoke <code>apply_async</c...
1
2016-09-05T20:00:01Z
39,355,161
<p>See <code>delivery_info</code> on <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#context" rel="nofollow">Task context</a>.</p>
1
2016-09-06T17:59:58Z
[ "python", "celery" ]
How to get the title of links in the html page using BeautifulSoup python?
39,336,994
<p>Consider the html :</p> <pre><code>&lt;li&gt;&lt;img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /&gt;&lt;a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"&gt; Student Notice &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;img alt="SangamUniversity-animated" class="newimg" src="images...
-1
2016-09-05T20:00:45Z
39,337,147
<p>Which python and BeautifulSoup do you use? In case of python2x and BS v. 3:</p> <pre><code>from BeautifulSoup import BeautifulSoup text = """&lt;li&gt;&lt;img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /&gt;&lt;a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"&gt; Studen...
0
2016-09-05T20:14:33Z
[ "python", "web-scraping", "beautifulsoup", "urllib2" ]
How to get the title of links in the html page using BeautifulSoup python?
39,336,994
<p>Consider the html :</p> <pre><code>&lt;li&gt;&lt;img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /&gt;&lt;a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"&gt; Student Notice &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;img alt="SangamUniversity-animated" class="newimg" src="images...
-1
2016-09-05T20:00:45Z
39,337,174
<p>You don't need <code>urllib</code> if you already have the html...urllib is used to make a request to a web server which then returns the html, you can simply do this when you have the html</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; a = """&lt;li&gt;&lt;img alt="SangamUniversity-animated...
0
2016-09-05T20:17:13Z
[ "python", "web-scraping", "beautifulsoup", "urllib2" ]
ElementTree Remove Element
39,337,042
<p>Python noob here. Wondering what's the cleanest and best way to <strong>remove</strong> all the "<code>profile</code>" tags with <code>updated</code> attribute value of <code>true</code>. </p> <p>I have tried the following code but it's throwing: <strong>SyntaxError("cannot use absolute path on element")</strong></...
1
2016-09-05T20:05:27Z
39,337,426
<p>If you are using <code>xml.etree.ElementTree</code>, you should use <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove" rel="nofollow"><code>remove()</code></a> method to remove a node, but this requires you to have the parent node reference. Hence, the solutio...
0
2016-09-05T20:39:16Z
[ "python", "xml", "python-2.7", "scripting", "elementtree" ]
Adding Acces-Control-Allow-Origin to app.yml
39,337,067
<p>I'm following these instructions from Google App Engine docs :</p> <p><a href="https://cloud.google.com/appengine/docs/python/config/appref" rel="nofollow">https://cloud.google.com/appengine/docs/python/config/appref</a></p> <p>If you search for CORS, you'll see the example I am trying to copy. </p> <p>My app.yam...
1
2016-09-05T20:07:04Z
39,337,637
<p>Unfortunately that's not valid <a href="http://yaml.org/" rel="nofollow">yaml</a>.</p> <p>You have an indentation problem. Also you have to quote the <code>*</code>. Should be:</p> <pre><code>handlers: - url: /.* script: main.app http_headers: Access-Control-Allow-Origin: "*" </code></pre>
4
2016-09-05T20:59:23Z
[ "python", "google-app-engine", "cors" ]
Quickly filter elements in Python array by minimum and maximum values
39,337,082
<p>I have a somewhat large <code>numpy</code> array of floats (<code>large_array</code>, ~2e7 elements). I need to generate a new array, filtering out all elements beyond certain minimum and maximum values.</p> <p>I can do this with a simple:</p> <pre><code>import numpy as np large_array = np.random.uniform(0., 10000...
3
2016-09-05T20:08:26Z
39,337,132
<p>try this:</p> <pre><code>In [18]: large_array.shape Out[18]: (20000000,) In [26]: new = large_array[(large_array &gt;= min_val) &amp; (large_array &lt;= max_val)] In [27]: new Out[27]: array([ 814.24315891, 1611.53346093, 624.31833231, ..., 1999.08383068, 2212.9825087 , 1786.08963269]) In [28]: new.shape ...
1
2016-09-05T20:13:13Z
[ "python", "arrays", "numpy" ]
Convert a string to JSON
39,337,100
<p>I would like to convert this string to a JSON dict:</p> <pre><code>{u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4...
2
2016-09-05T20:09:55Z
39,337,138
<p>Use <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> to convert string to valid Python object.</p> <blockquote> <p>Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided ...
2
2016-09-05T20:14:09Z
[ "python", "json" ]
Convert a string to JSON
39,337,100
<p>I would like to convert this string to a JSON dict:</p> <pre><code>{u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4...
2
2016-09-05T20:09:55Z
39,337,257
<p>Try this,</p> <pre><code>import json data = {u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4088', u'0.0', u'0.2', u...
0
2016-09-05T20:24:52Z
[ "python", "json" ]
Testing if a pandas DataFrame exists
39,337,115
<p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all. Let's say I want to test and see if a certain DataFrame has been created yet or not. My first thought would be to test for it like this:</p> <pre><code>if df1: # do something </code></pre> <p>However, that cod...
3
2016-09-05T20:11:45Z
39,337,192
<blockquote> <p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all</p> </blockquote> <p>They Pythonic way of indicating "nothing" is via <code>None</code>, and for checking "not nothing" via</p> <pre><code>if df1 is not None: ... </code></pre> <p>I am not sure ho...
3
2016-09-05T20:18:03Z
[ "python", "pandas" ]
Testing if a pandas DataFrame exists
39,337,115
<p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all. Let's say I want to test and see if a certain DataFrame has been created yet or not. My first thought would be to test for it like this:</p> <pre><code>if df1: # do something </code></pre> <p>However, that cod...
3
2016-09-05T20:11:45Z
39,338,381
<p><strong><em>Option 1</em></strong> (my preferred option)</p> <h3>This is @Ami Tavory's</h3> <p><strong><em>Please select his answer if you like this approach</em></strong></p> <p>It is very idiomatic python to initialize a variable with <code>None</code> then check for <code>None</code> prior to doing something w...
3
2016-09-05T22:30:55Z
[ "python", "pandas" ]
How do i get each byte into a list
39,337,208
<p>I want to open a MIDI file and analyse each byte. But i am VERY unfamiliar with handeling bytes and bits. Midi's are written in hexadecimal if that does any difference.</p> <p>What i want to do is put each byte into a list, and then make a for loop to check each one. How would i go about doing that?</p> <p>I've co...
1
2016-09-05T20:19:23Z
39,337,451
<p>just completed your code to scan the first 40 bytes of data. It prints the decimal value as well as the hex value using both C-like <code>%</code> formatting and more pythonic <code>format</code> method, which may be more understandable if format specification is in hex.</p> <p>midi file has been downloaded <a href...
1
2016-09-05T20:41:10Z
[ "python", "list", "python-3.x", "byte", "midi" ]
How to access values of list inside list- Python
39,337,263
<p>I'm trying to make a game using pygame but I'm having problems with lists inside other lists.</p> <p>inside the class of Enemy/Enemy 2 i have the following code:</p> <pre><code>ei = [[Enemy(), Enemy()][Enemy2()]] for wave in ei: if self in wave: print(ei.index(self)) </code></pre> <p>The object is in...
0
2016-09-05T20:25:21Z
39,337,480
<p>I tried to codify your question:</p> <pre><code>ei = [[Enemy(), Enemy()][Enemy2()]] for wave in ei: if self In wave: print(ei.index(self)) </code></pre> <p>What do you mean by <code>[[Enemy(), Enemy()][Enemy2()]]</code>? You are trying to get the <code>Enemy2()</code>th element of <code>[Enemy(), Enemy...
0
2016-09-05T20:44:19Z
[ "python", "list", "nested-lists" ]
How to access values of list inside list- Python
39,337,263
<p>I'm trying to make a game using pygame but I'm having problems with lists inside other lists.</p> <p>inside the class of Enemy/Enemy 2 i have the following code:</p> <pre><code>ei = [[Enemy(), Enemy()][Enemy2()]] for wave in ei: if self in wave: print(ei.index(self)) </code></pre> <p>The object is in...
0
2016-09-05T20:25:21Z
39,344,148
<p>I am guessing, and there are several problems in your example. But maaaybe you want this:</p> <pre><code>for index, wave in enumerate(ei): if self in wave: print(index) </code></pre> <p>See my comments or elaborate your question --as already recommended by other users, provide a MCVE and fix/explain th...
0
2016-09-06T08:28:22Z
[ "python", "list", "nested-lists" ]
Python 3.5.1 Formatting Floats Issue
39,337,275
<p>I am trying to create a app that compares loans with various interest rates for a programming assignment. I generally understand what I am doing and could complete the assignment but am running into an issue with the .format function. I'm trying to format floats so that they can be printed as results. Here is my cod...
1
2016-09-05T20:26:10Z
39,337,333
<p>You can omit the numbering (and it'll be auto-numbered for you), but you still need to use the <code>:</code> colon to separate the identifier from the formatting specification:</p> <pre><code>print("{:&lt;20.6f}{:&lt;20.6f}{:&lt;20.6f}".format(interest_rate, monthly_payment, total_payment)) </code></pre> <p>Witho...
3
2016-09-05T20:31:46Z
[ "python", "floating-point", "python-3.5" ]
tkinter won't update entry box with function
39,337,348
<p>Lately I've bean learning how to use the tkinter module in Python 3 to create a GUI. Unfortunately I've become stuck on an issue where my Entry widgets won't update. To understand the problem I wrote a short test case that populates an Entry widget with the string 'hello'.</p> <pre><code>class SettingsWindow(): ...
1
2016-09-05T20:33:01Z
39,337,468
<p>The ttk widgets are particularly sensitive to the garbage collector. Make <code>start_time</code> an instance variable rather than a local variable.</p>
0
2016-09-05T20:42:58Z
[ "python", "python-3.x", "user-interface", "tkinter" ]
Python implementation of Mergesort for Linked list doesn't work
39,337,414
<p>I couldn't find a simple implementation of <code>Merge Sort</code> in Python for <code>Linked Lists</code> anywhere. Here's what I tried:</p> <h3>Definition for singly-linked list:</h3> <pre><code>class ListNode: def __init__(self, x): self.val = x self.next = None </code></pre> <h3>Merge Sor...
2
2016-09-05T20:38:17Z
39,338,528
<p>Try changing the lines in the mergeSort function to:</p> <pre><code>leftHalf = mergeSortLinkedList(leftHalf) rightHalf = mergeSortLinkedList(rightHalf) </code></pre>
2
2016-09-05T22:51:04Z
[ "python", "algorithm", "sorting", "linked-list", "mergesort" ]
Python implementation of Mergesort for Linked list doesn't work
39,337,414
<p>I couldn't find a simple implementation of <code>Merge Sort</code> in Python for <code>Linked Lists</code> anywhere. Here's what I tried:</p> <h3>Definition for singly-linked list:</h3> <pre><code>class ListNode: def __init__(self, x): self.val = x self.next = None </code></pre> <h3>Merge Sor...
2
2016-09-05T20:38:17Z
39,339,667
<p>You don't use the return values from the recursive call. The code should be:</p> <pre><code>def mergeSortLinkedList(A): if A is None or A.next is None: return A leftHalf, rightHalf = splitTheList(A) left = mergeSortLinkedList(leftHalf) right = mergeSortLinkedList(rightHalf) return mer...
1
2016-09-06T02:09:54Z
[ "python", "algorithm", "sorting", "linked-list", "mergesort" ]
imports python3 in another folder
39,337,460
<p>When I run launch.py it fails and when I run main.py directly it works. launch.py just imports and runs main.py. Why?</p> <pre><code>├── dir │   ├── bla.py │   ├── __init__.py │   └── main.py ├── __init__.py └── launch.py launch.py --------- #!/usr/bin/env python...
1
2016-09-05T20:41:58Z
39,337,533
<p>I believe I see the answer... <br> You have not defined main, perhaps try that. The reason why it works when called directly is because Python scripts are run in the order in which functions appear unless a specific function is called.</p> <p>Try changing main.py to</p> <pre><code>import bla def mainfunction(): ...
-1
2016-09-05T20:47:34Z
[ "python", "import", "module", "folder" ]
imports python3 in another folder
39,337,460
<p>When I run launch.py it fails and when I run main.py directly it works. launch.py just imports and runs main.py. Why?</p> <pre><code>├── dir │   ├── bla.py │   ├── __init__.py │   └── main.py ├── __init__.py └── launch.py launch.py --------- #!/usr/bin/env python...
1
2016-09-05T20:41:58Z
39,338,088
<p>Using your layout and with the following files, we don't have problems.</p> <h3>launch.py</h3> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from dir import main if __name__ == "__main__": main. main() </code></pre> <h3>main.py</h3> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- try: ...
1
2016-09-05T21:50:32Z
[ "python", "import", "module", "folder" ]
Using ROS message classes outside of ROS
39,337,522
<p>I have a ROS node written in Python that captures messages and writes them to disk (e.g. using <code>pickle</code>). I want to use these files later, in another Python script, outside of ROS, but I need to import the message classes.</p> <p>Is that possible?</p> <p>Thanks!</p>
1
2016-09-05T20:46:54Z
39,611,619
<p>Unfortunately I don't think it's possible to just import the message files outside of any ROS dependencies. For example, if you look inside one of the generated message class files:</p> <pre><code>---/your_catkin_ws/devel/lib/python2.7/dist-packages/your_package/msg/_Message.py </code></pre> <p>You will see that i...
1
2016-09-21T08:45:06Z
[ "python", "ros" ]
How to get 2 or more LinearRegionItem to overlap each other
39,337,545
<p>I have added 2 <code>LinearRegionItems</code> to a <code>pyqtgraph</code> plot. When I move the boundary of 1 over the other, the boundary never overlaps the other.</p> <p>I would like to know how to allow overlapping. This is a functionality that I need, where I am selecting different regions of the data plot to b...
1
2016-09-05T20:48:26Z
39,413,892
<p>Sorry, there was a bug in my code which was handling the case where a part of one LinearRegionItem overlapped with another LinearRegionItem.</p> <p>Now I see that one linearRegionItem can lie on top of another one.</p> <p>Consider this solved</p>
0
2016-09-09T14:26:10Z
[ "python", "pyqtgraph" ]
How to implement simple Monte Carlo function in pymc
39,337,589
<p>I'm trying to get my head around how to implement a Monte Carlo function in python using pymc to replicate a spreadsheet by Douglas Hubbard in his book <a href="http://www.howtomeasureanything.com/wp-content/uploads/2015/03/HTMA_3rd_Ch6.xlsx" rel="nofollow">How to Measure Anything</a></p> <p>My attempt was:</p> <p...
1
2016-09-05T20:53:07Z
39,347,046
<p>Ah, it was a copy and paste error. </p> <p>I'd called three distributions by the same name.</p> <p>Here's the code that works.</p> <pre><code>import numpy as np import pandas as pd from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform, Normal, Stochastic, MCMC, Model %matplotlib inline im...
0
2016-09-06T10:42:10Z
[ "python", "pymc" ]
Python Error in Displaying Image
39,337,619
<p>On this Image</p> <p><a href="http://i.stack.imgur.com/GLcQa.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/GLcQa.jpg" alt="enter image description here"></a></p> <p>I am trying to apply:</p> <pre><code>from PIL import Image img0 = PIL.Image.open('Entertainment.jpg') img0 = np.float32(img0) showarray(img0...
1
2016-09-05T20:56:56Z
39,337,768
<p><code>Image</code> is a module that you imported </p> <pre><code>from PIL import Image </code></pre> <p>You can't call it </p> <pre><code>Image(data=f.getvalue()) </code></pre> <p>There's a show method that may be useful </p> <pre><code>img0 = PIL.Image.open('Entertainment.jpg') img0.show() </code></pre>
0
2016-09-05T21:14:40Z
[ "python", "image", "python-imaging-library" ]
embedding resources in python scripts
39,337,630
<p>I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.</p> <p>Little example to clarify, let's say I got this small snippet:</p> <pre><code>from StringIO i...
1
2016-09-05T20:58:45Z
39,337,715
<p>The best way to go about this is converting your picture into a python string, and have it in a separate file called something like <code>resources.py</code>, then you simply parse it.</p> <p>If you are looking to embed the whole thing inside a single binary, then you're looking at something like <a href="http://py...
3
2016-09-05T21:08:16Z
[ "python", "embedded-resource" ]
embedding resources in python scripts
39,337,630
<p>I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.</p> <p>Little example to clarify, let's say I got this small snippet:</p> <pre><code>from StringIO i...
1
2016-09-05T20:58:45Z
39,350,365
<p>You might find the following class rather useful for embedding resources in your program. To use it, call the <code>package</code> method with paths to the files that you want to embed. The class will print out a <code>DATA</code> attribute that should be used to replace the one already found in the class. If you wa...
1
2016-09-06T13:34:10Z
[ "python", "embedded-resource" ]
Sorting function in Pandas, returns messy data
39,337,648
<p>I am trying to sort data in a CSV file using sort function in Pandas using the following code. I have 229 rows in original file. But the output of sorting is 245 rows, because some of the data in a field were printed in the next row and some of the rows do not have any value. </p> <pre><code>sample=pd.read_csv("s...
4
2016-09-05T21:00:44Z
39,338,666
<p>You could try to remove the newlines in your problem column.</p> <pre><code>sample=pd.read_csv("sample.csv" , encoding='latin-1', skipinitialspace=True) sample["problem_column"] = (sample["problem_column"]. apply(lambda x: " ".join([word for word in x.split()]) ...
2
2016-09-05T23:12:49Z
[ "python", "sorting", "pandas" ]
C function to Python (different results)
39,337,652
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p> <p>This is the C version of the code which works:</p> <pre><code>int main(void) { uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76}; uint8_t len = 5; uint8_t chan = 0x64; btLeWhiten(pac, len, chan);...
3
2016-09-05T21:01:11Z
39,337,731
<p>In C you are writing data from 0 to len-1 but in Python you are writing data from -1 to len-2. Remove the -1 from this line:</p> <pre><code>data[len - idx -1 ] ^= m </code></pre> <p>like this</p> <pre><code>data[len - idx] ^= m </code></pre> <p>you also need to put this line outside the if:</p> <pre><code>white...
1
2016-09-05T21:10:19Z
[ "python", "bit-manipulation", "lfsr" ]
C function to Python (different results)
39,337,652
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p> <p>This is the C version of the code which works:</p> <pre><code>int main(void) { uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76}; uint8_t len = 5; uint8_t chan = 0x64; btLeWhiten(pac, len, chan);...
3
2016-09-05T21:01:11Z
39,337,750
<p><code>whitenCoeff &lt;&lt;= 1</code> in C becomes 0 after a while because it is a 8-bit data.</p> <p>In python, there's no such limit, so you have to write:</p> <pre><code>whitenCoeff = (whitenCoeff&lt;&lt;1) &amp; 0xFF </code></pre> <p>to mask higher bits out.</p> <p>(don't forget to check vz0 remark on array b...
1
2016-09-05T21:12:31Z
[ "python", "bit-manipulation", "lfsr" ]
C function to Python (different results)
39,337,652
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p> <p>This is the C version of the code which works:</p> <pre><code>int main(void) { uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76}; uint8_t len = 5; uint8_t chan = 0x64; btLeWhiten(pac, len, chan);...
3
2016-09-05T21:01:11Z
39,337,824
<p>You've got a few more problems.</p> <ol> <li><code>whitenCoeff &lt;&lt;= 1;</code> is outside of the <code>if</code> block in your C code, but it's inside of the <code>if</code> block in your Python code.</li> <li><code>data[len - idx -1 ] ^= m</code> wasn't translated correctly, it works backwards from the C code....
1
2016-09-05T21:20:42Z
[ "python", "bit-manipulation", "lfsr" ]
C function to Python (different results)
39,337,652
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p> <p>This is the C version of the code which works:</p> <pre><code>int main(void) { uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76}; uint8_t len = 5; uint8_t chan = 0x64; btLeWhiten(pac, len, chan);...
3
2016-09-05T21:01:11Z
39,370,028
<p>I solved it by anding the python code with 0xFF. That keeps the variable from increasing beyond 8 bits.</p>
0
2016-09-07T12:30:52Z
[ "python", "bit-manipulation", "lfsr" ]
Tensorflow slim train and validate inception model
39,337,691
<p>I'm trying to fine tune inception models, and validate it with test data. But all the examples given at tensorflow slime web page only either fine-tuning or testing, there is not any example that doing both at same graph and session. </p> <p>Basically I want to this. </p> <pre><code>with tf.Graph().as_default(): ...
0
2016-09-05T21:04:18Z
39,358,463
<p>Does calling train with number_of_steps=10 and then using the evaluation code work?</p>
-1
2016-09-06T21:58:45Z
[ "python", "neural-network", "tensorflow", "deep-learning", "conv-neural-network" ]
What is the default value that Python chooses when adding two variables?
39,337,729
<p>Suppose we have the following context: </p> <pre><code>x = 3 y = 4 z = x + y </code></pre> <p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point...
1
2016-09-05T21:10:12Z
39,337,755
<p>When <em>mixing</em> types, you'll always get the 'wider' type, where a complex number is wider than float, which in turn is wider than an integer. When both values are the same type (so <em>not</em> mixing types), you will just get that one type as the result.</p> <p>From the <a href="https://docs.python.org/2/lib...
3
2016-09-05T21:13:11Z
[ "python", "python-3.x", "types" ]
What is the default value that Python chooses when adding two variables?
39,337,729
<p>Suppose we have the following context: </p> <pre><code>x = 3 y = 4 z = x + y </code></pre> <p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point...
1
2016-09-05T21:10:12Z
39,337,860
<p>For example:</p> <pre><code>&gt;&gt;&gt; type(3 + 4) &lt;class 'int'&gt; &gt;&gt;&gt; type(3.0 + 4) &lt;class 'float'&gt; &gt;&gt;&gt; type(3.0 + 4.0) &lt;class 'float'&gt; </code></pre> <p>If the difference between a float or integer is important to your application, explicitly convert the user input into a float...
1
2016-09-05T21:25:19Z
[ "python", "python-3.x", "types" ]
What is the default value that Python chooses when adding two variables?
39,337,729
<p>Suppose we have the following context: </p> <pre><code>x = 3 y = 4 z = x + y </code></pre> <p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point...
1
2016-09-05T21:10:12Z
39,338,116
<p>The <em>mixing</em> rules Martijn described are a good way to think about built in numeric types. More broadly, any object can support arithmetic operators such as <code>+</code> and <code>*</code> as long as the methods are implemented. With objects <code>a</code> and <code>b</code> when you apply an arithmetic ope...
0
2016-09-05T21:54:09Z
[ "python", "python-3.x", "types" ]
What is the default value that Python chooses when adding two variables?
39,337,729
<p>Suppose we have the following context: </p> <pre><code>x = 3 y = 4 z = x + y </code></pre> <p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point...
1
2016-09-05T21:10:12Z
39,338,265
<p>This is easy to test. By default, if you perform arithmetic on two integers, Python will store the result as an integer. You can see that here.</p> <pre><code>&gt;&gt;&gt; x = 1 &gt;&gt;&gt; y = 2 &gt;&gt;&gt; z = x + y &gt;&gt;&gt; type(z) &lt;class 'int'&gt; </code></pre> <p>The type function will tell you what ...
1
2016-09-05T22:16:04Z
[ "python", "python-3.x", "types" ]
Distance beetween lists in Python 3
39,337,736
<p>Python 3.4</p> <p>I have many lists, like that:</p> <pre><code>A=[(1,2),(3,4),..] ... N=[(10,2),(3,4),...] </code></pre> <p>I want to merge the lists, if exist minimum distance (between their points) &lt; 10.</p> <p>measure is <code>sqrt((x1-x2)^2+(y1-y2)^2)</code></p> <p>For example we have list with 3 matrix:...
0
2016-09-05T21:11:07Z
39,337,944
<p>I suggest you look at some form of <a href="https://en.wikipedia.org/wiki/Cluster_analysis" rel="nofollow">cluster analysis</a></p>
0
2016-09-05T21:34:42Z
[ "python", "python-3.x" ]
Why Python scope my variable outside my function?
39,337,756
<p>i start with Python. I like to try new language. So i've got a "simple" problem about scope and Python.</p> <p>Here is a recursive function</p> <pre><code>def foo(myarray) if myarray == False: myarray = [[0] * 5 for _ in range(5)] myarray[0][0] = 1 "some code ..." foo(myarray) myarray = False foo(m...
-6
2016-09-05T21:13:26Z
39,337,818
<p>Disregarding the myriad of syntax errors, your <code>myarray</code> variable seems to be declared globally and that's why it has global scope?</p>
2
2016-09-05T21:20:04Z
[ "python", "python-3.x" ]
Python UDF for Pig in Azure Data Factory On demand HDInsight cluster
39,337,791
<p>How to include python UDF for pig when using Azure data factory and azure blob to store the pig script?</p>
0
2016-09-05T21:16:47Z
39,651,902
<p>@abu,</p> <p>I recommend you can refer to the official document to konw how to use Pig and Python On Azure HDinsight. <a href="https://azure.microsoft.com/en-in/documentation/articles/hdinsight-python/" rel="nofollow">https://azure.microsoft.com/en-in/documentation/articles/hdinsight-python/</a> If you store your p...
0
2016-09-23T03:02:17Z
[ "python", "azure", "apache-pig", "hdinsight", "azure-data-factory" ]
Rabbitmq one queue multiple consumers
39,337,821
<p>I've multiple consumers which are polling on the same queue, and checking the queue every X seconds, basically after X seconds it could be that at least two consumers can launch <code>basic.get</code> at the very same time. </p> <p>Question are:<br> 1.If at least two consumers at the same time can get the same mes...
1
2016-09-05T21:20:17Z
39,340,382
<blockquote> <p>1.If at least two consumers at the same time can get the same message?</p> </blockquote> <p>no - a single message will only be delivered to a single consumer.</p> <p>Because of that, your scenario #2 doesn't come into play at all. </p> <p>You'll never have 2 consumers working on the same message, u...
2
2016-09-06T03:51:29Z
[ "python", "python-2.7", "rabbitmq", "pika" ]
bytes casted to int by a list constructor
39,337,840
<p>I want to read <em>n</em> bytes a binary file and store each byte in a list. However, when I do so, each byte is casted into an <code>int</code>.</p> <p>First I create a random file.</p> <pre><code>$ head -c 16 &gt; random.file </code></pre> <p>Then I try to read it:</p> <pre class="lang-py prettyprint-override"...
2
2016-09-05T21:22:46Z
39,338,141
<p>Any single byte you access in a list of bytes is just a single int value:</p> <pre><code>&gt;&gt;&gt; b"foo"[0] 102 </code></pre> <p>If you want to create a new list that consists of lists of bytes with the length 1, you'll have to do that explicitly:</p> <pre><code>&gt;&gt;&gt; c = b"foo" &gt;&gt;&gt; l = [] &gt...
1
2016-09-05T21:57:16Z
[ "python", "types", "casting" ]
Python iterating from the middle of a cycle to before the start
39,337,849
<p>I've been working on programming a board game to practice python. I use a cycle to do turn order like this:</p> <pre><code>turncycle = [0,1,2,3] for turnindex in cycle(turncycle): #. #...turn stuff #...turnindex is used for active player #. </code></pre> <p>What I want to do is given a turn index s...
0
2016-09-05T21:23:29Z
39,337,913
<p>What about something like this?</p> <pre><code>def next_cycle(lst): return turncycle[1:] + turncycle[:1] turncycle = [0, 1, 2, 3] for turnindex in range(len(turncycle)): turncycle = next_cycle(turncycle) print turncycle </code></pre>
1
2016-09-05T21:31:22Z
[ "python", "list", "iteration", "cycle" ]
Python iterating from the middle of a cycle to before the start
39,337,849
<p>I've been working on programming a board game to practice python. I use a cycle to do turn order like this:</p> <pre><code>turncycle = [0,1,2,3] for turnindex in cycle(turncycle): #. #...turn stuff #...turnindex is used for active player #. </code></pre> <p>What I want to do is given a turn index s...
0
2016-09-05T21:23:29Z
39,338,299
<p>Cobbled together something from the <a href="https://docs.python.org/2.7/library/itertools.html#recipes" rel="nofollow">itertools recipes</a></p> <pre><code>import itertools a = [0,1,2,3,4,5,6,7] def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions ...
1
2016-09-05T22:20:06Z
[ "python", "list", "iteration", "cycle" ]
How to Detect an Empty Value
39,337,888
<p>I'm currently making a Python script for account creation. My script is as follows:</p> <pre><code>import csv nms = [] with open('nms.txt', newline='') as inputfile: for row in csv.reader(inputfile): nms.append(row) counter = 0 ## End of tings while True: print ("Please enter your us...
1
2016-09-05T21:28:27Z
39,337,936
<p>I'm not sure I see the need for the counter variable, but you can check if an item exists in an iterable object with <code>in</code></p> <pre><code>if usernm in nms: # user already exists </code></pre> <blockquote> <p>I've tried to stop the program checking if the username is equal to a blank value</p> </bl...
0
2016-09-05T21:33:46Z
[ "python", "input", null, "value" ]
python copy files with time stamp
39,337,896
<p>I would like to copy file with date time stamp. the below code is not working on windows. I am new to python so please help me. </p> <pre><code>import shutil import datetime shutil.copyfile('C:\\Users\\Documents\\error.log','C:\\Users\\Documents\datetime.now().strftime("%Y%m%d-%H%M%S").log') </code></pre>
2
2016-09-05T21:29:39Z
39,337,988
<p>In your code, you have the code enclosed in the string. You need to run the code out of the string, and combine it with the string. A solution would be</p> <pre><code>import shutil import datetime shutil.copyfile('C:\\Users\\Documents\\error.log','C:\\Users\\Documents\' + datetime.now().strftime("%Y%m%d-%H%M%S") + ...
1
2016-09-05T21:39:26Z
[ "python", "shutil", "copyfile" ]
Accessing <li> element with no class id using Beautiful soup
39,337,909
<p>I am trying to scrape the companies in the li in the ul table under final result. The source code looks like this</p> <p>import string import re import urllib2 import datetime import bs4 from bs4 import BeautifulSoup</p> <p>class AJSpider(object):</p> <pre><code>def __init__(self): print ("initisizing") s...
4
2016-09-05T21:30:48Z
39,337,929
<p>Find the <code>h3</code> element <em>by text</em> and get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow">following <code>ul</code> list</a>:</p> <pre><code>ul = soup.find("h3", text="Final Result").find_next_sibling("ul") for li in ul.fin...
3
2016-09-05T21:33:07Z
[ "python", "html", "beautifulsoup", "html-lists" ]
Django. Customize action for model
39,338,058
<p>I need to edit the "Add Object" action in the admin. It needs to redirect the user to a custom cause the logic required for adding objects is too complex to be managed in the admin. So, how do I make this possible? i.e:</p> <p><a href="http://i.stack.imgur.com/ChoP7.jpg" rel="nofollow"><img src="http://i.stack.imgu...
0
2016-09-05T21:47:27Z
39,338,221
<p>Override <code>change_list_template</code> html, the block <code>object-tools-items</code>. It's where add button is placed.</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): change_list_template = 'change_list.html' </code></pre> <p>In your <code>change_list.html</code></p> <pre><code>{% extends "admin/ch...
1
2016-09-05T22:10:24Z
[ "python", "django", "django-admin" ]
How to reference Django application url in admin index template
39,338,080
<p>I'm currently making changes to the admin/index.html template and I need to reference the url in my application using the name space 'hello' in a href tag for a link, but I'm having trouble doing at the admin level. The name of my application is clean and the url pattern in urls.py file is below.</p> <pre><code>ur...
0
2016-09-05T21:49:29Z
39,338,374
<p>You can simply use:</p> <pre><code>&lt;div&gt; &lt;h3&gt;Hello World&lt;/h3&gt; &lt;a href="{% url 'hello' %}"&gt;Test&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Django provides the ability to "reverse" URLs (i.e. provided the name of the URL, and arguments if necessary, the actual URL is generated) in order ...
2
2016-09-05T22:29:44Z
[ "python", "html", "django" ]
Kivy Checkbox restrict click
39,338,204
<p>I am trying to create a checkbox in my float layout area. I am getting the checkbox to generate but every time I click it goes from True to False even if it not on the box. Could someone provide some insight?</p> <p>My code:</p> <pre><code>from kivy.app import App from kivy.lang import Builder from kivy.uix.checkb...
0
2016-09-05T22:07:50Z
39,339,591
<p>Try placing the CheckBox in a Widget and it works. I mean:</p> <pre><code>FloatLayout: Widget: CheckBox: pos_hint: {"x":0.2, "y":0.2} on_release: True TextInput: id: a font_size: 25 password: True pos_hint: {"x":0.5, "y":0.5} size_hint:...
0
2016-09-06T01:57:53Z
[ "python", "python-2.7", "checkbox", "kivy", "kivy-language" ]
How can I print out the correct response based on input?
39,338,238
<p>I'm new to Python and I have a very simple problem that I'd like explained to me. I'm making a text adventure game and I'd like to be able to call another function inside a function so my code is organized better. </p> <p>This is what I have that's working:</p> <pre><code>def displayIntro(): print("You come to...
-1
2016-09-05T22:12:09Z
39,338,254
<p>You're not passing the return value of <code>choosePath()</code> to <code>checkPath()</code>. It should be:</p> <pre><code>path = choosePath() checkPath(path) </code></pre> <p>Or as a one-liner:</p> <pre><code>checkPath(choosePath()) </code></pre>
2
2016-09-05T22:15:04Z
[ "python" ]
How can I print out the correct response based on input?
39,338,238
<p>I'm new to Python and I have a very simple problem that I'd like explained to me. I'm making a text adventure game and I'd like to be able to call another function inside a function so my code is organized better. </p> <p>This is what I have that's working:</p> <pre><code>def displayIntro(): print("You come to...
-1
2016-09-05T22:12:09Z
39,338,261
<p>You have to pass the return value of <code>choosePath</code> to <code>checkPath</code>.</p> <pre><code>checkPath(choosePath()) </code></pre> <p><code>checkPath</code> takes a parameter, so you need to supply a value. That value is the return value of <code>choosePath</code>, either "LEFT" or "RIGHT". Once you pass...
1
2016-09-05T22:15:39Z
[ "python" ]
Forbidden (CSRF token missing or incorrect.) Django + AngularJs
39,338,369
<p>When I try to render to my second page in my django framework I get following error. I think that there is something wrong with my url page and views.py but can't figure it out, nothing gives a step forward..</p> <pre><code>Forbidden (CSRF token missing or incorrect.): /renderbonds [06/Sep/2016 00:21:55] "POST /ren...
0
2016-09-05T22:29:30Z
39,338,383
<p>The issue is not with your urls or your views, but with your template. Try adding <code>{% csrf_token %}</code> nested under your <code>&lt;form&gt;&lt;/form&gt;</code> tags in your template. </p> <pre><code>&lt;form action="{% url 'renderbonds'%}" method="post" &gt; &lt;input type="submit" value="calculate bon...
2
2016-09-05T22:31:08Z
[ "python", "angularjs", "django" ]
Python crash course 8-10
39,338,405
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p> <blockquote> <p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which pr...
2
2016-09-05T22:34:05Z
39,338,427
<p>To do this, you can append to a string and reassign to add words to the end of each element:</p> <pre><code>magician += " the great" </code></pre> <p>Here, the <code>+=</code> operator appends a string, then reassigns, which is equivalent to the following:</p> <pre><code>magician = magician + " the great" </c...
1
2016-09-05T22:37:08Z
[ "python" ]
Python crash course 8-10
39,338,405
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p> <blockquote> <p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which pr...
2
2016-09-05T22:34:05Z
39,338,440
<p>Okay, you already know how to iterate through the list. You want to make a similar function, where you modify the string referred to my <code>magician</code> to say, "the Great".</p> <p>So, if you had a string "Smedley" and you wanted to change that to a string "Smedley the Great" how would you do it?</p> <p><stro...
1
2016-09-05T22:38:29Z
[ "python" ]
Python crash course 8-10
39,338,405
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p> <blockquote> <p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which pr...
2
2016-09-05T22:34:05Z
39,338,445
<p>The question asks you to modify <code>magician_names</code>. Since each entry in <code>magician_names</code> is a <code>str</code>, and <code>strs</code> are unmodifiable, you cannot simply modify each <code>str</code> in <code>magician_names</code> by appending <code>" the great"</code> to it. Instead, you need to ...
1
2016-09-05T22:38:54Z
[ "python" ]
Quadractic Formula mix up
39,338,450
<p>So I made a python code that solves for x using the quadratic formula. Everything works out in the end except for the signs. For instance, if you want to factor x^2 + 10x + 25, my code outputs -5, -5 when the answer should be 5, 5.</p> <pre><code>def quadratic_formula(): a = int(input("a = ")) b = int(input...
3
2016-09-05T22:39:47Z
39,338,510
<p>Your solution is fine, let's prove it using <a href="http://www.sympy.org/en/index.html" rel="nofollow">sympy</a>:</p> <pre><code>&gt;&gt;&gt; (x**2+10*x+25).subs(x,-5) 0 </code></pre> <p>As you can see, -5 is one of the roots while 5</p> <pre><code>&gt;&gt;&gt; (x**2+10*x+25).subs(x,5) 100 </code></pre> <p>is n...
5
2016-09-05T22:48:48Z
[ "python", "math", "quadratic" ]
Curl "Connection Refused" when connecting to server with external IP address
39,338,451
<p>I've created a RESTful server and I can successfully make requests and get responses when I use my local IP address. I would like it to be exposed externally to the internet. I set up a port forwarding rule but I cannot seem to get things working. From what I'm reading the "Connection Refused" with (7) means some...
1
2016-09-05T22:39:49Z
39,338,861
<p>I find it strange that you'd be getting connection refused from within the local network because the router should be able to detect that the external IP is a reference to itself. </p> <p>That ability may depend on the router, but that's been my experience with networking. </p> <p>That being said, if you'd like to...
1
2016-09-05T23:49:17Z
[ "python", "curl", "networking", "portforwarding" ]
Time complexity for a sublist in Python
39,338,520
<p>In Python, what is the time complexity when we create a sublist from an existing list?</p> <p>For example, here data is the name of our existing list and list1 is our sublist created by slicing data.</p> <pre><code>data = [1,2,3,4,5,6..100,...1000....,10^6] list1 = data[101:10^6] </code></pre> <p>What is the run...
4
2016-09-05T22:49:38Z
39,338,537
<p>Getting a list slice in python is <code>O(M - N)</code> / <code>O(10^6 - 101)</code></p> <p><a href="https://wiki.python.org/moin/TimeComplexity">Here</a> you can check python list operations time complexity </p> <p>By underneath, python lists are represented like arrays. So, you can iterate starting on some inde...
7
2016-09-05T22:51:56Z
[ "python", "performance", "list", "big-o", "sublist" ]
Cut a polygon with two lines in shapely
39,338,550
<p>I am trying to cut a <code>shapely.geometry.Polygon</code> instance into two parts with two lines. For example, in the code below, <code>polygon</code> is a ring and if we cut it with <code>line1</code> and <code>line2</code> we should get two partial rings, one w/ 270 degrees and one with 90 degrees. Would there be...
1
2016-09-05T22:53:56Z
39,340,336
<p>Ken Watford answered <a href="http://community-gispython-org-community-projects.955323.n3.nabble.com/Community-Shapely-how-to-split-a-polygon-with-a-line-td1915160.html" rel="nofollow">here</a> about using <code>buffer</code> and <code>difference</code> to do the trick, w/ the drawback of losing a bit of the area. A...
1
2016-09-06T03:46:11Z
[ "python", "shapely" ]
How to place marker on one line and get coordinates
39,338,575
<p>1)I want to place a marker on one line,(between two points) in function of the lenght of the line.</p> <p>2)I want to know the coordinates of this point/marker.</p> <pre><code>import matplotlib.pyplot as plt import math x1 = 0 x2 = 9 y1 = 5 y2 = 7 plt.plot((x1, x2), (y1, y2)) lenghtline1 = math.sqrt((x1-x2)**2 + (...
0
2016-09-05T22:58:24Z
39,339,391
<p>Point with distance <code>len</code> to the first point will have coordinates</p> <pre><code> x = x1 + (x2-x1) * len / lenghtline1 y = y1 + (y2-y1) * len / lenghtline1 </code></pre>
0
2016-09-06T01:22:45Z
[ "python", "python-3.x", "numpy", "math", "matplotlib" ]
How to place marker on one line and get coordinates
39,338,575
<p>1)I want to place a marker on one line,(between two points) in function of the lenght of the line.</p> <p>2)I want to know the coordinates of this point/marker.</p> <pre><code>import matplotlib.pyplot as plt import math x1 = 0 x2 = 9 y1 = 5 y2 = 7 plt.plot((x1, x2), (y1, y2)) lenghtline1 = math.sqrt((x1-x2)**2 + (...
0
2016-09-05T22:58:24Z
39,350,709
<pre><code>from pylab import * from scipy import interpolate x = rand(21).cumsum() # create some 21 random x values y = rand(len(x)) # the corresponding y values plot(x, y, ".-") xc = x[:-1] + diff(x)/2. yc = interpolate.interp1d(x, y, kind="linear")(xc) # (xc, yc) are the marker positions lengths = sqrt(diff(x)**...
0
2016-09-06T13:49:43Z
[ "python", "python-3.x", "numpy", "math", "matplotlib" ]
Can't connect to mysql using sqlalchemy. Library not loaded error
39,338,631
<p>I am trying to run a simple test code to connect ti a mysql db using sql alchemy. The code is as follows:</p> <pre><code>from sqlalchemy import (create_engine, Table, Column, Integer, String, MetaData) import settings import sys try: db = create_engine('mysql://daniel:dani@localhost/test') db.connect() exce...
0
2016-09-05T23:06:03Z
39,338,962
<p>I also had some problems with SQLAlchemy with mysql, i changed localhost in the create_engine to 127.0.0.1:port, and also had to use pymysql. Ended up working with this:</p> <p><code>engine = create_engine('mysql+pymysql://user:[email protected]:port/db')</code></p> <p>pymysql is installed via pip.</p>
0
2016-09-06T00:05:50Z
[ "python", "mysql", "sqlalchemy" ]
Can't connect to mysql using sqlalchemy. Library not loaded error
39,338,631
<p>I am trying to run a simple test code to connect ti a mysql db using sql alchemy. The code is as follows:</p> <pre><code>from sqlalchemy import (create_engine, Table, Column, Integer, String, MetaData) import settings import sys try: db = create_engine('mysql://daniel:dani@localhost/test') db.connect() exce...
0
2016-09-05T23:06:03Z
39,341,459
<p>You are using python , so you have add mysqldb with mysql. Try the below code.</p> <pre><code>try: db = create_engine('mysql+mysqldb://daniel:dani@localhost/test') db.connect() except: print('opps ', sys.exc_info()[1]) </code></pre>
0
2016-09-06T05:49:25Z
[ "python", "mysql", "sqlalchemy" ]
How to get results from pyparsing Forward object?
39,338,654
<p>Let us assume we have the following string</p> <pre><code>string = """ object obj1{ attr1 value1; object obj2 { attr2 value2; } } object obj3{ attr3 value3; attr4 value4; } """ </code></pre> <p>There is a nested object, and we use Forward to parse this. </p> <pre><code>from pyparsi...
1
2016-09-05T23:10:41Z
39,339,359
<p>I was able to work around this by using <code>listAllMatches=True</code> in the setResultsNames function. This gave me as asXML() result that had structure that I could retrieve information from. It still relies on the order of the XML and requires using zip for get the <code>name</code> and <code>value</code> for a...
2
2016-09-06T01:17:03Z
[ "python", "pyparsing" ]
How to get results from pyparsing Forward object?
39,338,654
<p>Let us assume we have the following string</p> <pre><code>string = """ object obj1{ attr1 value1; object obj2 { attr2 value2; } } object obj3{ attr3 value3; attr4 value4; } """ </code></pre> <p>There is a nested object, and we use Forward to parse this. </p> <pre><code>from pyparsi...
1
2016-09-05T23:10:41Z
39,438,974
<p>While you have successfully processed your input string, let me suggest some refinements to your grammar.</p> <p>When defining a recursive grammar, one usually wants to maintain some structure in the output results. In your case, the logical piece to structure is the content of each object, which is surrounded by o...
1
2016-09-11T17:50:04Z
[ "python", "pyparsing" ]
how to reference angular component template from django app
39,338,707
<p>I have the following angular component:</p> <pre><code>angular. module('phoneList'). component('phoneList', { templateUrl: 'phone-list.template.html', controller: function PhoneListController() { this.phones = [ { name: 'Nexus S', snippet: 'Fast just got faster with Nexus S.', ...
0
2016-09-05T23:20:37Z
39,338,813
<p>Templates in the <code>templates</code> folder in Django are available to the template loader only. They are not served and can not be accessed via HTTP directly. But that is what Angular does.</p> <p>If you need to render the template in Django, make sure you have created a view and an endpoint for it in your <cod...
2
2016-09-05T23:38:47Z
[ "python", "angularjs", "node.js", "django" ]
ElementTree Write to an XML
39,338,733
<p>What's the easiest way to write an edited XML root to a new file? This is what I have so far and it's throwing <strong>AttributeError: 'module' object has no attribute 'write'</strong> <br> PS: I can't use any other api besides ElementTree.</p> <pre><code>import xml.etree.ElementTree as ET from xml.etree.ElementTre...
0
2016-09-05T23:25:18Z
39,338,848
<p><strong>AttributeError: 'module' object has no attribute 'write'</strong> is saying that you cannot call the write method directly from ElementTree class, it is not a static method, try using <code>tree.write('file-after-edits.xml')</code>, tree is your object from ElementTree.</p>
0
2016-09-05T23:45:40Z
[ "python", "xml", "elementtree" ]
ElementTree Write to an XML
39,338,733
<p>What's the easiest way to write an edited XML root to a new file? This is what I have so far and it's throwing <strong>AttributeError: 'module' object has no attribute 'write'</strong> <br> PS: I can't use any other api besides ElementTree.</p> <pre><code>import xml.etree.ElementTree as ET from xml.etree.ElementTre...
0
2016-09-05T23:25:18Z
39,338,941
<p>Your <code>tree</code> is a <code>ElementTree</code> object which provides a <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" rel="nofollow"><code>write()</code></a> method to write the tree. For example:</p> <pre><code>#Process XML here tree.write('file...
0
2016-09-06T00:02:26Z
[ "python", "xml", "elementtree" ]
Pandas pd.DataFrame converts to Tuples instead of Dataframe
39,338,746
<p>I first use BeautifulSoup:</p> <pre><code>mydivs = soup.findAll('div', {"class": "content"}) </code></pre> <p>so that each <code>mydiv</code> in <code>mydivs</code> looks like this for example:</p> <pre><code>&lt;div class="content"&gt;A number of hats by me &lt;br/&gt;&lt;br/&gt;three now though ... &lt;/div&gt;...
2
2016-09-05T23:26:45Z
39,338,796
<p>shape is an attribute of <code>DF</code>. That attribute is a <code>tuple</code>. You are trying to call it with the <code>()</code> which is throwing the error. If you want the shape just do <code>DF.shape</code></p> <pre><code>print DF.shape </code></pre> <p><strong><em>not</em></strong></p> <pre><code>print DF...
4
2016-09-05T23:35:01Z
[ "python", "pandas", "dataframe" ]
Finding the highest value with the given constraints
39,338,764
<pre><code>c = [416,585,464] A0 = [100,50,200] A1 = [100,100,200] A2 = [100,150,100] A3 = [100,200,0] A4 = [100,250,0] b = [300,300,300,300,300] for num in A0,A1,A2,A3,A4: t0 = num[0]*1 + num[1]*1 + num[2]*1 t1 = num[0]*0 + num[1]*1 + num[2]*0 t2 = num[0]*0 + num[1]*0 + num[2]*0 t3 = num[0]*0 + num[1...
-3
2016-09-05T23:29:24Z
39,340,214
<p>I guess this does what you want—at least it produces sums from the data similar to those you mentioned in your question. I found your sample code is <em>very</em> misleading since it doesn't produce the kind of <code>t_</code> values you refer to in the written problem description below it.</p> <pre><code>from i...
0
2016-09-06T03:28:13Z
[ "python", "arrays", "list" ]
Insertion-sort error in Python
39,338,851
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p> <pre><code>line 16, in &lt;module&gt; if listNums[x] &lt; listNums[i]: </code></pre> <p>For this program: </p> <pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38] x = 1 i = 0 ...
0
2016-09-05T23:46:34Z
39,338,863
<p>Chances are it's a bounds error because <code>x</code> eventually increments up to <code>len(listNums)</code> which is 1 beyond the bounds of the zero-indexed array.</p> <p>Try only iterating through <code>range(0, len(listNums)-1)</code>.</p>
1
2016-09-05T23:49:31Z
[ "python", "python-3.x", "insertion-sort" ]
Insertion-sort error in Python
39,338,851
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p> <pre><code>line 16, in &lt;module&gt; if listNums[x] &lt; listNums[i]: </code></pre> <p>For this program: </p> <pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38] x = 1 i = 0 ...
0
2016-09-05T23:46:34Z
39,339,420
<p>I'd just like to point out that there is a better way to do it, namely</p> <pre><code>listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38] listNums.sort() print listNums </code></pre> <p>which gives </p> <pre><code>[21, 32, 34, 38, 43, 54, 65, 65, 76, 98] =&gt; None </code></pre> <p>(compiled on repl.it)</p> ...
0
2016-09-06T01:28:39Z
[ "python", "python-3.x", "insertion-sort" ]
Insertion-sort error in Python
39,338,851
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p> <pre><code>line 16, in &lt;module&gt; if listNums[x] &lt; listNums[i]: </code></pre> <p>For this program: </p> <pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38] x = 1 i = 0 ...
0
2016-09-05T23:46:34Z
39,363,625
<p>This is not an <code>insertion sort error</code> In the last iteration i.e. len(listNums)th iteration, the value of x goes beyond the length of list that's why it gives <code>IndexError: list index out of range</code> </p>
0
2016-09-07T07:21:58Z
[ "python", "python-3.x", "insertion-sort" ]
Parsing with multiple loops opening files
39,339,007
<p>I'm trying to count the number of lines contained by a file that looks like this:</p> <pre><code>-StartACheck ---Lines-- -EndACheck -StartBCheck ---Lines-- -EndBCheck </code></pre> <p>with this:</p> <pre><code>count=0 z={} for line in file: s=re.search(r'\-+Start([A-Za-z0-9]+)Check',line) if s: ...
-1
2016-09-06T00:14:44Z
39,340,686
<p>This kind of problem can be resolved with a <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow">finite state machine</a>. This is a complex matter that would need more explanation than what I could write here. You should look into it to further understand what you can do with it. </p> <p>But...
0
2016-09-06T04:31:03Z
[ "python", "python-2.7" ]
How to write large JSON data?
39,339,044
<p>I have been trying to write large amount (>800mb) of data to JSON file; I did some fair amount of trial and error to get this code:</p> <pre><code>def write_to_cube(data): with open('test.json') as file1: temp_data = json.load(file1) temp_data.update(data) file1.close() with open('test.js...
0
2016-09-06T00:21:56Z
39,340,868
<p>So the problem is that you have a long operation. Here are a few approaches that I usually do:</p> <ol> <li>Optimize the operation: This rarely works. I wouldn't recommend any superb library that would parse the json a few seconds faster</li> <li>Change your logic: If the purpose is to save and load data, probably ...
0
2016-09-06T04:51:10Z
[ "python", "json" ]
Is it possible write a single def for both ComboBox and RadioBox events?
39,339,124
<p>Here the code writes parts of a string selected by the user. After each event, the TextCtrl gains one more piece of the string until it's time to the user to copy the text to the clipboard. It works fine, but it's not elegant since there is too much repetition in the code.</p> <pre><code>import wx import pypercl...
0
2016-09-06T00:36:11Z
39,339,386
<p>You can use <code>e.GetEventObject()</code> to get access to widget which send event.</p> <p>And then you can use <code>isinstance</code> to recognize widget type.</p> <pre><code>def onSelect(self, e): widget = e.GetEventObject() if isinstance(widget, wx.RadioBox): self.t3.AppendText(str(widget.GetStri...
0
2016-09-06T01:20:54Z
[ "python", "wxpython" ]
pandas read_csv and keep only certain rows (python)
39,339,142
<p>I am aware of the skiprows that allows you to pass a list with the indices of the rows to skip. However, I have the index of the rows I want to keep.</p> <p>Say that my cvs file looks like this for millions of rows:</p> <pre><code> A B 0 1 2 1 3 4 2 5 6 3 7 8 4 9 0 </code></pre> <p>The list of indices i would li...
2
2016-09-06T00:39:34Z
39,339,691
<p>I think you would need to find the number of lines first, like <a href="http://stackoverflow.com/a/1019572/2029132">this</a>.</p> <pre><code>num_lines = sum(1 for line in open('myfile.txt')) </code></pre> <p>Then you would need to delete the indices of <code>index_list</code>:</p> <pre><code>to_exclude = [i for i...
2
2016-09-06T02:14:44Z
[ "python", "pandas" ]
Get href from leftmost column in table with XPath
39,339,188
<p>I am attempted to extract <code>href</code> text from a table here: <a href="https://en.wikipedia.org/wiki/List_of_first-person_shooters" rel="nofollow">https://en.wikipedia.org/wiki/List_of_first-person_shooters</a></p> <p>Here is the top of the table:</p> <pre><code>&lt;table class="wikitable sortable" style="fo...
2
2016-09-06T00:47:17Z
39,339,244
<p>Only first column use <code>&lt;th&gt;</code> and <code>&lt;i&gt;</code> so use it</p> <pre><code>tree.xpath('//table[@class="wikitable sortable"]//th//a/@href') </code></pre> <p>or</p> <pre><code>tree.xpath('//table[@class="wikitable sortable"]//i/a/@href') </code></pre>
-1
2016-09-06T00:57:51Z
[ "python", "html", "xml", "xpath", "lxml" ]
Get href from leftmost column in table with XPath
39,339,188
<p>I am attempted to extract <code>href</code> text from a table here: <a href="https://en.wikipedia.org/wiki/List_of_first-person_shooters" rel="nofollow">https://en.wikipedia.org/wiki/List_of_first-person_shooters</a></p> <p>Here is the top of the table:</p> <pre><code>&lt;table class="wikitable sortable" style="fo...
2
2016-09-06T00:47:17Z
39,339,558
<blockquote> <p>I only want the first column from each row</p> </blockquote> <p>This XPath,</p> <pre><code> //table[@class="wikitable sortable"]//tr/*[1]//a/@href </code></pre> <p>will select only the <code>a/@href</code> found in the first column of each <code>tr</code>:</p> <pre><code>/wiki/007_Legends /wiki/00...
1
2016-09-06T01:53:33Z
[ "python", "html", "xml", "xpath", "lxml" ]
Difference between self.request and request in Django class-based view
39,339,221
<p>In django, for class-based view like <code>ListView</code> and <code>DetailView</code>, methods like <code>get()</code> or <code>post()</code> or other functions defined by developer take parameters include <code>self</code> and <code>request</code>. I learnt that in <code>self</code> these is actually a <code>self....
3
2016-09-06T00:52:41Z
39,340,089
<p>For a subclass of <code>View</code>, they're the same object. <code>self.request = request</code> is set in <code>view</code> function that <code>as_view()</code> returns. I looked into the history, but only found setting <code>self.request</code> and then immediately passing request into the view function.</p>
0
2016-09-06T03:11:32Z
[ "python", "django" ]
Django passing a variable to Httpresponseredirect throws exception
39,339,237
<p>The problem I Have right now is that I get a :</p> <p>Reverse for 'documentation' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []</p> <p>when I try to redirect to another view using HttpResponseRedirect</p> <p>Here is my urls.py</p> <pre><code> url(r'^documentation/([0-9])/$...
0
2016-09-06T00:56:22Z
39,339,361
<p>I think the problem is not with the HttpResponseRedirect, but with the call to reverse().</p> <p>When you pass args, you should use the list notation for the values:</p> <pre><code>return HttpResponseRedirect(reverse('documentation', args=[b])) </code></pre> <p>That should help, at least.</p>
0
2016-09-06T01:17:26Z
[ "python", "django" ]
What data structure should I use to process large amounts of text data?
39,339,357
<p>I'm trying to do some text classication using scikit-learn's TfidfVectorizer and the Nearest Neighbor algorithm.</p> <p>I need to find similarity metrics between two data sets containing 18000 entries each. I'm unsure about what data structure can be best used to calculate what I think should be 18000*18000 similar...
-1
2016-09-06T01:16:48Z
39,339,780
<p>If you don't need any intermediate data for further analyses you can use a generator to hold your data points then run the algorithms through generators calls. Otherwise you'd probably want a list.</p>
0
2016-09-06T02:29:29Z
[ "python", "numpy", "scikit-learn", "text-processing" ]
Grok learning python programming
39,339,374
<p>I am wondering how to solve this problem:</p> <p>You are curious about the most popular and least popular colours of cars and decide to write a program to calculate the frequency of car colours.</p> <p>Your program should read in the colour of each car until a blank line is entered, and then print out (in any orde...
-4
2016-09-06T01:19:47Z
39,339,438
<p>You have to call <code>input</code> multiple times with a sentinel value, then count the objects, then iterate over the keys and values, and then print a formatted string for each count. Reasonably straightforward with one line of code:</p> <pre><code>print(*('Cars that are {}: {}'.format(*item) for item in __impor...
0
2016-09-06T01:32:54Z
[ "python" ]
Iterate through the rows of a dataframe and reassign minimum values by group
39,339,401
<p>I am working with a dataframe that looks like this.</p> <pre><code> id time diff 0 0 34 nan 1 0 36 2 2 1 43 7 3 1 55 12 4 1 59 4 5 2 2 -57 6 2 10 8 </code></pre> <p>What is an efficient way find the minimum values for 'time' by id, then set 'diff' to nan at those minimum values. I am ...
4
2016-09-06T01:24:38Z
39,339,552
<p>You can group the time by id and calculate a logical vector where if the time is minimum within the group, the value is True, else False, and use the logical vector to assign <code>NaN</code> to the corresponding rows:</p> <pre><code>import numpy as np import pandas as pd df.loc[df.groupby('id')['time'].apply(lambd...
4
2016-09-06T01:52:43Z
[ "python", "pandas" ]
Iterate through the rows of a dataframe and reassign minimum values by group
39,339,401
<p>I am working with a dataframe that looks like this.</p> <pre><code> id time diff 0 0 34 nan 1 0 36 2 2 1 43 7 3 1 55 12 4 1 59 4 5 2 2 -57 6 2 10 8 </code></pre> <p>What is an efficient way find the minimum values for 'time' by id, then set 'diff' to nan at those minimum values. I am ...
4
2016-09-06T01:24:38Z
39,339,583
<p><code>groupby('id')</code> and use <code>idxmin</code> to find the location of minimum values of <code>'time'</code>. Finally, use <code>loc</code> to assign <code>np.nan</code></p> <pre><code>df.loc[df.groupby('id').time.idxmin(), 'diff'] = np.nan df </code></pre> <p><a href="http://i.stack.imgur.com/qsTwZ.png">...
6
2016-09-06T01:57:03Z
[ "python", "pandas" ]
Start inner loop from position of the outer
39,339,476
<p>In my example I have two loops. One nested within the other. Is there a way I can start the inner loop from the index of the outer. Here is pseudo code. </p> <pre><code>arrayOfWords = ["one","two","five"] arrayOfWords2 = ["one","two","three","four","five"] tottalWordlist = [] for index, jString in enumerate(arrayOf...
0
2016-09-06T01:40:25Z
39,339,509
<p>You're almost there. You just need to add the starting index to the <code>range</code> object.</p> <pre><code>arrayOfWords2Count = range(indexClone, len(arrayOfWords2)) for i in arrayOfWords2Count: if gWord == arrayOfWords2[i]: </code></pre> <p>Also, you don't need to subtract one from the endpoint, as that en...
4
2016-09-06T01:45:07Z
[ "python" ]
Start inner loop from position of the outer
39,339,476
<p>In my example I have two loops. One nested within the other. Is there a way I can start the inner loop from the index of the outer. Here is pseudo code. </p> <pre><code>arrayOfWords = ["one","two","five"] arrayOfWords2 = ["one","two","three","four","five"] tottalWordlist = [] for index, jString in enumerate(arrayOf...
0
2016-09-06T01:40:25Z
39,339,590
<p>in my understanding, you are looking for whether outer list's element in inner list begin with outer element's index.</p> <pre><code>arrayOfWords = ["one","two","five"] arrayOfWords2 = ["one","two","three","four","five"] print [ item for i,item in enumerate(arrayOfWords) if item in arrayOfWords2[i:] ] ['one', 't...
2
2016-09-06T01:57:44Z
[ "python" ]
The right syntax to use near '''?
39,339,512
<p>I am running a Python bot which connects to a SQL database and updates values in tables.</p> <p>I have the following code:</p> <p><code>mycursor.execute("SELECT * FROM reputation WHERE username = '" + str(critiquer) + "'")</code></p> <p>I am receiving the error "...check the manual that corresponds to your MySQL ...
-2
2016-09-06T01:45:17Z
39,339,561
<p>Try using a parametrized query:</p> <pre><code>mycursor.execute("SELECT * FROM reputation WHERE username = '?'", critiquer) </code></pre>
1
2016-09-06T01:54:22Z
[ "python", "mysql" ]
How to transform several lists of words to a pandas dataframe?
39,339,560
<p>I have file .txt that contains a list of words like this:</p> <pre><code>5.91686268506 exclusively, catering, provides, arms, georgia, formal, purchase, choose 5.91560417296 hugh, senlis 5.91527936181 italians 5.91470429433 soil, cultivation, fertile 5.91468087491 increases, moderation .... 5.91440227412 farmers, d...
2
2016-09-06T01:54:02Z
39,339,609
<p>Because you have space between words and if you specify space as delimiter, it will naturally separate them. To get what you need, you can try to set the <code>sep</code> as a regular expression <code>(?&lt;!,)</code>, <code>?&lt;!</code> is a negative look behind syntax, which means separate on space only when it i...
6
2016-09-06T02:00:10Z
[ "python", "python-3.x", "csv", "pandas" ]
Django custom context_processors in render_to_string method
39,339,569
<p>I'm building a function to send email and I need to use a context_processor variable inside the HTML template of the email, but this don't work.</p> <p>Example:</p> <pre><code>def send_email(plain_body_template_name, html_body_template_name): plain_body = loader.render_to_string(plain_body_template_name, conte...
0
2016-09-06T01:55:24Z
39,340,015
<p>Assuming you're using the <code>django</code> backend in your <code>TEMPLATE</code> with</p> <p><code>'BACKEND': 'django.template.backends.django.DjangoTemplates', </code></p> <p>django is seeing that you haven't passed in a request and opting for a basic <code>Context</code> to wrap your dict instead of a <code>R...
1
2016-09-06T03:02:31Z
[ "python", "django" ]
Why am I getting the following error: NameError: name 'models' is not defined
39,339,593
<p>Whenever I run the program, I get the following error:</p> <pre><code>NameError at /table/ name 'models' is not defined </code></pre> <p>It says that there's an error on line 4 in my views. </p> <p>Here is my views.py:</p> <pre><code>from django.shortcuts import render def display(request): return render(re...
-1
2016-09-06T01:57:55Z
39,339,611
<p>You are referencing <code>models.Book</code> in your view, but you have not imported <code>models</code>. In your views.py you need to do <code>from myapp import models</code>. Or you can do <code>from myapp.models import Book</code> and change it in your view function to just <code>Book.objects.all()</code>.</p>
4
2016-09-06T02:00:45Z
[ "python", "django" ]
Removing "\n"s when printing sentences from text file in python?
39,339,621
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p> <pre><code>file = open('11.txt','r+') alice = file.read() print(alice[:500]) </code></pre> <p>Output is:</p> <pre><code>ALICE'S ADVENTURES IN WONDERLA...
-1
2016-09-06T02:01:53Z
39,339,657
<p>The <code>\n</code>, or newline, characters come from the blank lines in the file. They are an escape character that basically acts like a hit on the 'return' key. On the first line, it ends with a <code>\n</code> character, and next line also ends in a <code>\n</code>.</p> <p>To remove them what you can do is loop...
0
2016-09-06T02:08:27Z
[ "python", "split", "format", "sentence" ]
Removing "\n"s when printing sentences from text file in python?
39,339,621
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p> <pre><code>file = open('11.txt','r+') alice = file.read() print(alice[:500]) </code></pre> <p>Output is:</p> <pre><code>ALICE'S ADVENTURES IN WONDERLA...
-1
2016-09-06T02:01:53Z
39,339,696
<p>You may not want to use regex, but I would do:</p> <pre><code>import re new_sentences = [] for s in sentences: new_sentences.append(re.sub(r'\n{2,}', '\n', s)) </code></pre> <p>This should replace all instances of two or more <code>'\n'</code> with a single newline, so you still have newlines, but don't have "...
2
2016-09-06T02:16:28Z
[ "python", "split", "format", "sentence" ]
Removing "\n"s when printing sentences from text file in python?
39,339,621
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p> <pre><code>file = open('11.txt','r+') alice = file.read() print(alice[:500]) </code></pre> <p>Output is:</p> <pre><code>ALICE'S ADVENTURES IN WONDERLA...
-1
2016-09-06T02:01:53Z
39,339,706
<p>You'll understand where the <code>\n</code> characters come from with this little example:</p> <pre><code>alice = """ALICE'S ADVENTURES IN WONDERLAND Lewis Carroll THE MILLENNIUM FULCRUM EDITION 3.0 CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very tired of sitting by her sister on the bank, an...
1
2016-09-06T02:17:46Z
[ "python", "split", "format", "sentence" ]