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
Writing intersection data to new CSV
39,636,426
<p>I have 2 CSV files which have a list of unique words. After I complete my intersection on them I get the results, but when I try to write it to a new file it creates a very large sized file of almost 155MB, when it should be well below 2MB.</p> <p><strong>Code:</strong></p> <pre><code>alist, blist = [], [] with o...
-1
2016-09-22T10:19:56Z
39,636,462
<p>You're <em>writing</em> the entire set <code>res</code> to the file on each iteration. You probably want to write the rows instead:</p> <pre><code>for row in res: writer.writerow([row]) </code></pre>
2
2016-09-22T10:21:34Z
[ "python", "csv" ]
Writing intersection data to new CSV
39,636,426
<p>I have 2 CSV files which have a list of unique words. After I complete my intersection on them I get the results, but when I try to write it to a new file it creates a very large sized file of almost 155MB, when it should be well below 2MB.</p> <p><strong>Code:</strong></p> <pre><code>alist, blist = [], [] with o...
-1
2016-09-22T10:19:56Z
39,638,303
<p>Apart from writing the whole set each iteration you also don't need to create multiple sets and lists, you can use <em>itertools.chain</em>:</p> <pre><code>from itertools import chain with open("SetA-unique.csv") as file_a, open("SetB-unique.csv") as file_b,open("SetA-SetB.csv", 'w') as inter : r1 = csv.reade...
0
2016-09-22T11:52:28Z
[ "python", "csv" ]
How to avoid quotes from a comma separated string joined from a list in python
39,636,437
<p>I have created a comma separated string by joining strings from a list in Python 3.5 and use it to write it to an INI file using configobj. Here is a sample Python script used in a Ubuntu 16.04 terminal:</p> <pre><code>sudo python3 &lt;&lt; EOP from configobj import ConfigObj config=ConfigObj("myconfig.ini") confi...
0
2016-09-22T10:20:26Z
39,636,679
<p>Commas are reserved for field separation and so you cannot have (unless you <a href="http://stackoverflow.com/a/39636774/2681632">really want to</a>) an unquoted string value with commas in it. Apparently you do want to have a list of values, so just pass a list as the value:</p> <pre><code>from configobj import Co...
2
2016-09-22T10:32:22Z
[ "python", "string", "csv", "quotes" ]
How to avoid quotes from a comma separated string joined from a list in python
39,636,437
<p>I have created a comma separated string by joining strings from a list in Python 3.5 and use it to write it to an INI file using configobj. Here is a sample Python script used in a Ubuntu 16.04 terminal:</p> <pre><code>sudo python3 &lt;&lt; EOP from configobj import ConfigObj config=ConfigObj("myconfig.ini") confi...
0
2016-09-22T10:20:26Z
39,636,774
<p>Another solution is to use the <code>list_values</code> keyword:</p> <pre><code>config = ConfigObj('myconfig.ini', list_values=False) </code></pre> <p><a href="https://configobj.readthedocs.io/en/latest/configobj.html#configobj-specifications" rel="nofollow">As the documentation says</a>, if <code>list_values=Fals...
2
2016-09-22T10:37:56Z
[ "python", "string", "csv", "quotes" ]
python - regex for matching text between two characters while ignoring backslashed characters
39,636,439
<p>I am trying to use python to get text between two dollar signs ($), but the dollar signs should <strong>not</strong> start with a backslash i.e. \$ (this is for a LaTeX rendering program). So if this is given</p> <pre><code>$\$x + \$y = 5$ and $3$ </code></pre> <p>This is what should be outputted</p> <pre><code>...
1
2016-09-22T10:20:28Z
39,636,533
<p>You can use this lookaround based regex that excluded escaped characters:</p> <pre><code>&gt;&gt;&gt; text = r'$\$x + \$y = 5$ and $3$' &gt;&gt;&gt; re.findall(r'(?&lt;=\$)([^$\\]*(?:\\.[^$\\]*)*)(?=\$)', text) ['\\$x + \\$y = 5', ' and ', '3'] </code></pre> <p><a href="https://regex101.com/r/zA7zE2/1" rel="nofoll...
1
2016-09-22T10:25:02Z
[ "python", "regex", "escaping" ]
Destroy function Tkinter
39,636,507
<p>In this program I am attempting to destroy all on screen widgets at the start of a new function and instantly re-create them on screen to replicate a new page appearing. I used the destroy function once already to "change pages" when clicking on the start button in the game menu which worked fine. </p> <p>However w...
0
2016-09-22T10:23:48Z
39,640,158
<pre><code>IntroCanvas.bind("&lt;Button-1&gt;", Activ1()) ^^ IntroCanvas.pack() </code></pre> <p>You are getting the error in above lines.</p> <p>Adding parentheses means, "<em>call</em> that function as soon as compiler reaches there". After <code>Activ1</code> gets called, it ...
1
2016-09-22T13:16:04Z
[ "python", "tkinter", "destroy", "tkinter-canvas" ]
SSH tunnel from Python is too slow to connect
39,636,740
<p>I'm connecting to a remote SQL database over SSH. If I set up the SSH connection from the Linux command line (using <code>ssh-add my_private_key.key</code> and then <code>ssh [email protected]</code>), it takes less than a second to connect. But if I do it from Python using <a href="https://github.com/pahaz/sshtun...
0
2016-09-22T10:36:21Z
39,830,029
<p>Doh! After posting this question I thought it would be a good idea to make sure sshtunnel was up-to-date - and it wasn't. So I've updated from 0.0.8.1 to the latest version (0.1.0) and my problem is solved!</p>
0
2016-10-03T11:00:29Z
[ "python", "linux", "python-3.x", "ssh" ]
Python: extract text request from url
39,636,797
<p>I try to extract users requests from url. I try to search answer, but I only find how to parse string. But I have a problem, that I should identify a lot of urls with request and when I try to get string with attribute, attributes with text are different. I mean when I try</p> <pre><code>pat = re.compile(r"\?\w+=(....
-1
2016-09-22T10:39:03Z
39,638,211
<p>You can access the text using a dictionary lookup to get the list, then access the first element of the list:</p> <pre><code>d = {'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\...
0
2016-09-22T11:49:08Z
[ "python", "urllib2", "urllib", "urlparse" ]
Module in Python
39,636,825
<p>Command :Import setuptools .</p> <p>Where python will going to search the setuptools ?</p> <p>Like command : Import ryu.hooks </p> <p>In this case it will search the ryu folder then import the code into the script which is calling it .</p> <p>-Ajay</p>
1
2016-09-22T10:40:12Z
39,636,916
<blockquote> <p>the interpreter first searches for a built-in module</p> </blockquote> <p><a href="https://docs.python.org/2/tutorial/modules.html#the-module-search-path" rel="nofollow">https://docs.python.org/2/tutorial/modules.html#the-module-search-path</a></p>
3
2016-09-22T10:44:52Z
[ "python" ]
extracting a set amount of lines from a Text file - Python
39,637,063
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p> <blockquote> <p>1 325315</p> <p>2 234265</p> <p>3 345345</p> <p>4 234234</p> <p>5 373432</p> <p>6 436721 </p> <p>7 3...
0
2016-09-22T10:53:14Z
39,637,423
<p>Something like this?</p> <pre><code>def extract(file, fr, to): f = open(file, "r+") [next(f) for i in range(fr)] return [f.readline() for i in range(to - fr)] </code></pre> <p>or extract only the 2nd column</p> <pre><code> return [f.readline().split()[1] for i in range(500)] </code></pre> <p>Out...
0
2016-09-22T11:11:03Z
[ "python", "text" ]
extracting a set amount of lines from a Text file - Python
39,637,063
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p> <blockquote> <p>1 325315</p> <p>2 234265</p> <p>3 345345</p> <p>4 234234</p> <p>5 373432</p> <p>6 436721 </p> <p>7 3...
0
2016-09-22T10:53:14Z
39,637,691
<p>Do like this.</p> <pre><code>l = [line for line in (open('xyz.txt','r')).readlines() if int(line.split()[0]) &gt; 3 and int(line.split()[0]) &lt; 6 ] </code></pre> <p>Output:(Output will be lines between 3 and 6)</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py ['4 234234\n', '5 373432\n'] C:\Users\...
0
2016-09-22T11:23:56Z
[ "python", "text" ]
extracting a set amount of lines from a Text file - Python
39,637,063
<p>let us imagine I have a text file with the following inside of it: (each line starts with a number and contains information next to it which I need) </p> <blockquote> <p>1 325315</p> <p>2 234265</p> <p>3 345345</p> <p>4 234234</p> <p>5 373432</p> <p>6 436721 </p> <p>7 3...
0
2016-09-22T10:53:14Z
39,637,791
<p>Assuming the indexes are not sequential</p> <pre><code>outList=[] with open('somefile') as f: for line in f: a=line.split() if 3&lt;int(a[0])&lt;6: outlist.append(a[1]) # or append(line), append(a) depending on needs </code></pre> <p>Or just use <code>numpy.loadtxt</code> and use ar...
0
2016-09-22T11:29:46Z
[ "python", "text" ]
python leading and trailing underscores in user defined functions
39,637,164
<p>How can i used the rt function, as i understand leading &amp; trailing underscores <code>__and__()</code> is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,</p> <pre><cod...
1
2016-09-22T10:58:28Z
39,637,203
<p>Because there are builtin methods that you can overriden and then you can use them, ex <code>__len__</code> -> <code>len()</code>, <code>__str__</code> -> <code>str()</code> and etc.</p> <p>Here is the <a href="https://docs.python.org/3/reference/datamodel.html#basic-customization" rel="nofollow">list of these func...
1
2016-09-22T11:00:54Z
[ "python" ]
python leading and trailing underscores in user defined functions
39,637,164
<p>How can i used the rt function, as i understand leading &amp; trailing underscores <code>__and__()</code> is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,</p> <pre><cod...
1
2016-09-22T10:58:28Z
39,637,230
<p>Python doesn't translate one name into another. Specific operations will <em>under the covers</em> call a <code>__special_method__</code> if it has been defined. For example, the <code>__and__</code> method is called by Python to hook into the <code>&amp;</code> operator, because the Python interpreter <em>explicitl...
3
2016-09-22T11:02:13Z
[ "python" ]
How do i read multiple json objects in django using POST method
39,637,305
<p>I am sending multiple json object to server and django views how to get this multiple json objects and extracting each key value.</p>
0
2016-09-22T11:05:35Z
39,637,315
<pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href='/static/js/file.txt' type="text/css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { $.get('static/js/file.txt', function (data) { va...
0
2016-09-22T11:06:10Z
[ "javascript", "jquery", "python", "html", "django" ]
How do I prevent `format()` from inserting newlines in my string?
39,637,407
<p>It might be my mistake, but <code>cmd = 'program {} {}'.format(arg1, arg2)</code> will always get a newline between the two args... like this <code>program 1\n2</code></p> <p>what should i do to put them in one line (<code>cmd</code> need to be passed to system shell)?</p>
-1
2016-09-22T11:10:22Z
39,637,460
<p><code>arg1</code> contains <code>\n</code>. Use <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow">strip()</a></p> <pre><code>cmd = 'program {} {}'.format(arg1.strip(), arg2.strip()) </code></pre>
3
2016-09-22T11:12:57Z
[ "python", "string-formatting" ]
Convert 1D object numpy array of lists to 2D numeric array and back
39,637,486
<p>Say I have this object array containing lists of the same length:</p> <pre><code>&gt;&gt;&gt; a = np.empty(2, dtype=object) &gt;&gt;&gt; a[0] = [1, 2, 3, 4] &gt;&gt;&gt; a[1] = [5, 6, 7, 8] &gt;&gt;&gt; a array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) </code></pre> <ol> <li><p>How can I convert this to a numeri...
2
2016-09-22T11:14:01Z
39,637,586
<p>One approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>np.concatenate</code></a> -</p> <pre><code>b = np.concatenate(a).reshape(len(a),*np.shape(a[0])) </code></pre> <p>The improvement suggest by <code>@Eric</code> to use <code>*np.shape(a[0])</...
3
2016-09-22T11:19:17Z
[ "python", "numpy" ]
Convert 1D object numpy array of lists to 2D numeric array and back
39,637,486
<p>Say I have this object array containing lists of the same length:</p> <pre><code>&gt;&gt;&gt; a = np.empty(2, dtype=object) &gt;&gt;&gt; a[0] = [1, 2, 3, 4] &gt;&gt;&gt; a[1] = [5, 6, 7, 8] &gt;&gt;&gt; a array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) </code></pre> <ol> <li><p>How can I convert this to a numeri...
2
2016-09-22T11:14:01Z
39,637,610
<p>You canuse np.vstack():</p> <pre><code>&gt;&gt;&gt; a = np.vstack(a).astype(int) </code></pre>
1
2016-09-22T11:20:25Z
[ "python", "numpy" ]
Convert 1D object numpy array of lists to 2D numeric array and back
39,637,486
<p>Say I have this object array containing lists of the same length:</p> <pre><code>&gt;&gt;&gt; a = np.empty(2, dtype=object) &gt;&gt;&gt; a[0] = [1, 2, 3, 4] &gt;&gt;&gt; a[1] = [5, 6, 7, 8] &gt;&gt;&gt; a array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) </code></pre> <ol> <li><p>How can I convert this to a numeri...
2
2016-09-22T11:14:01Z
39,637,657
<p>Here's an approach that converts the source NumPy array to lists and then into the desired NumPy array:</p> <pre><code>b = np.array([k for k in a]) b array([[1, 2, 3, 4], [5, 6, 7, 8]]) c = np.array([k for k in b], dtype=object) c array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) </code></pre>
0
2016-09-22T11:22:20Z
[ "python", "numpy" ]
Convert 1D object numpy array of lists to 2D numeric array and back
39,637,486
<p>Say I have this object array containing lists of the same length:</p> <pre><code>&gt;&gt;&gt; a = np.empty(2, dtype=object) &gt;&gt;&gt; a[0] = [1, 2, 3, 4] &gt;&gt;&gt; a[1] = [5, 6, 7, 8] &gt;&gt;&gt; a array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object) </code></pre> <ol> <li><p>How can I convert this to a numeri...
2
2016-09-22T11:14:01Z
39,637,667
<p>I found that round-tripping through <code>list</code> with <code>np.array(list(a))</code> was sufficient.</p> <p>This seems to be equivalent to using <code>np.stack(a)</code>.</p> <p>Both of these have the benefit of working in the more general case of converting a 1D array of ND arrays into an (N+1)D array.</p>
0
2016-09-22T11:22:46Z
[ "python", "numpy" ]
Python - Tkinter - Label Not Updating
39,637,493
<p>Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change. </p> <pre><code>from tkinter import * root = Tk(className="Page Calculator") read = IntVar...
0
2016-09-22T11:14:17Z
39,638,316
<p>To make the function do the job, you'd rather have your label:</p> <pre><code>leftresult_label = Label(root, textvariable=left) </code></pre> <p>Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,</p> <pre><code>def func1(): left.set(total.get() - r...
1
2016-09-22T11:53:19Z
[ "python", "tkinter", "label" ]
How verify function implemented?
39,637,629
<p>I want to find how <code>verify()</code> function from <code>Pillow</code> library implemented. In a source code i found only this:</p> <pre><code>def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actual...
0
2016-09-22T11:21:17Z
39,640,274
<p>A <a href="https://github.com/python-pillow/Pillow/issues/1408#issuecomment-139024840" rel="nofollow">comment on GitHub</a> explains:</p> <blockquote> <p>Image.[v]erify only checks the chunk checksums in png files, and is a no-op elsewhere.</p> </blockquote> <p>So the short answer is that you already did find th...
1
2016-09-22T13:21:56Z
[ "python", "pillow" ]
Jinja range raises TemplateSyntaxError in Django view
39,637,677
<p>In a django jinja2 tempate with the code</p> <pre><code>{% for i in range(10) %} foo {{ i }}&lt;br&gt; {% endfor %} </code></pre> <p>a <code>TemplateSyntaxError</code> is raised with the error message</p> <blockquote> <p>Could not parse the remainder: '(10)' from 'range(10)'</p> </blockquote> <p>What do I ...
-2
2016-09-22T11:23:23Z
39,647,252
<p>Django is not using Jinja2, but the Django template language. There is no range function in the Django template language.</p>
0
2016-09-22T19:19:35Z
[ "python", "django", "range", "jinja2" ]
how to iterate through a json that has multiple pages
39,637,713
<p>I have created a program that iterates through a multi-page json object.</p> <pre><code>def get_orgs(token,url): part1 = 'curl -i -k -X GET -H "Content-Type:application/json" -H "Authorization:Bearer ' final_url = part1 + token + '" ' + url pipe = subprocess.Popen(final_url, shell=False,stdout=subproce...
0
2016-09-22T11:25:15Z
39,645,162
<p>In my opinion using urllib2 or urllib.request would be a much better option than curl in order to make the code easier to understand, but if that's a constraint - I can work with that ;-)</p> <p>Assuming the json-response is all in one line (Otherwise your json.loads will throw an Exception), the task is pretty sim...
0
2016-09-22T17:18:33Z
[ "python", "json" ]
I keep getting this error and I dont know hove to fix it
39,637,744
<p>I open the file but is saying the file is not open. I stuck on what to do . I am new to python.</p> <p>Here is the error:</p> <pre><code>Traceback (most recent call last): File "\\users2\121721$\Computer Science\Progamming\task3.py", line 43, in &lt;module&gt; file.write(barcode + ":" + item + ":" + price + ":" ...
0
2016-09-22T11:27:07Z
39,637,778
<p>There is </p> <pre><code>if barcode!=UsersItem: open("data.txt","w") </code></pre> <p>You need to </p> <pre><code>if barcode!=UsersItem: file = open("data.txt","w") </code></pre> <p>Also the same error you have in <code>else</code> statement.</p> <p>And you should also consider refactoring your code, be...
3
2016-09-22T11:29:02Z
[ "python" ]
Can lambda be used instead of a method, as a key in sorted()?
39,637,810
<p>This is my first time asking a question. I've already got so much help from you without even asking. (Gratitude face). So, I found this useful piece of code from around here a few weeks ago.</p> <pre><code>import re def yearly_sort(value): numbers = re.compile(r'(\d+)') parts = numbers.split(value) par...
0
2016-09-22T11:30:41Z
39,637,974
<p>It definitely can be <code>lambda</code> function. For example look at that <a href="http://stackoverflow.com/questions/3766633/how-to-sort-with-lambda-in-python">question</a>.</p> <p>But if you have complex function you should never move it to <code>lambda</code> because readability significantly decreases.</p> <...
2
2016-09-22T11:38:29Z
[ "python", "python-3.x", "lambda" ]
Can lambda be used instead of a method, as a key in sorted()?
39,637,810
<p>This is my first time asking a question. I've already got so much help from you without even asking. (Gratitude face). So, I found this useful piece of code from around here a few weeks ago.</p> <pre><code>import re def yearly_sort(value): numbers = re.compile(r'(\d+)') parts = numbers.split(value) par...
0
2016-09-22T11:30:41Z
39,638,008
<p>you could squeeze it into a lambda provided that <code>numbers</code> is previously compiled (which increases performance)</p> <pre><code>numbers = re.compile(r'(\d+)') for file_name in sorted(files, key=lambda value : [int(x) if x.isdigit() else 0 for x in numbers.split(value)][1::2]): </code></pre> <p>In that ca...
0
2016-09-22T11:40:02Z
[ "python", "python-3.x", "lambda" ]
Blackjack Game - displaying ASCII Graphics / Multiline Strings
39,637,848
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p> <p>However I can't get them to print ...
1
2016-09-22T11:32:26Z
39,637,958
<p>With the way you're doing it, that would be very difficult. When you write</p> <pre><code>end='' </code></pre> <p>That only gets rid of the newline at the very end of the printed text. The problem is, every one of your cards has a new line on the right side:</p> <pre><code> ------- |J | | | | | #...
2
2016-09-22T11:37:30Z
[ "python", "python-3.x" ]
Blackjack Game - displaying ASCII Graphics / Multiline Strings
39,637,848
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p> <p>However I can't get them to print ...
1
2016-09-22T11:32:26Z
39,638,485
<p>I suggest you write a function that, given i and n, returns a string which represents line i of card n. You can then call that in a double nested loop, printing the results in sequence, to get the result you need. You can start by making an example of the output you want to see, to use as a reference while coding t...
2
2016-09-22T12:01:06Z
[ "python", "python-3.x" ]
Blackjack Game - displaying ASCII Graphics / Multiline Strings
39,637,848
<p>I'm pretty new to Python and currently trying to create a basic blackjack game using ASCII graphics to represent the cards. I've placed the card images in a list of multiline strings and the idea is to call the specific index for each one when a card needs to be displayed. </p> <p>However I can't get them to print ...
1
2016-09-22T11:32:26Z
39,640,926
<p>Interesting little problem. Here's a quick solution that I whipped up.</p> <p><code>class Card:</code></p> <pre><code>def topchar(char): return '|{} |'.format(char) def botchar(char): return '| {}|'.format(char) def print(char_list): top = ' ------- ' side ='| |' topout = '' ...
1
2016-09-22T13:49:30Z
[ "python", "python-3.x" ]
How to remove everything after the last number in a string
39,637,955
<p>I have strings like this:</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>My goal is to remove everything after the last number, so my desired output would be</p> <pre><code>w123 o456 t789 </code></pre> <p>It is not always the same ending, so <code>-- --</code> is just one example.</p> <pre><code>impo...
1
2016-09-22T11:37:21Z
39,637,977
<p>You can use:</p> <pre><code>&gt;&gt;&gt; w = 'w123 o456 t789-- --' &gt;&gt;&gt; re.sub(r'\D+$', '', w) 'w123 o456 t789' </code></pre> <p><code>\D+$</code> will remove 1 or more non-digit characters before end anchor <code>$</code>.</p>
7
2016-09-22T11:38:37Z
[ "python", "regex" ]
How to remove everything after the last number in a string
39,637,955
<p>I have strings like this:</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>My goal is to remove everything after the last number, so my desired output would be</p> <pre><code>w123 o456 t789 </code></pre> <p>It is not always the same ending, so <code>-- --</code> is just one example.</p> <pre><code>impo...
1
2016-09-22T11:37:21Z
39,637,986
<pre><code>st = 'w123 o456 t789-- --' print st.rstrip() "w123 o456 t789' </code></pre>
-1
2016-09-22T11:39:07Z
[ "python", "regex" ]
How to remove everything after the last number in a string
39,637,955
<p>I have strings like this:</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>My goal is to remove everything after the last number, so my desired output would be</p> <pre><code>w123 o456 t789 </code></pre> <p>It is not always the same ending, so <code>-- --</code> is just one example.</p> <pre><code>impo...
1
2016-09-22T11:37:21Z
39,638,161
<p>The point is that your expression contains <em>lazy</em> dot matching pattern and it matches up to and including the first one or more digits.</p> <p>You need to use <em>greedy</em> dot matching pattern to match up to the <em>last</em> digit, and capture that part into a capturing group. Then, use a <code>r'\1'</co...
1
2016-09-22T11:47:06Z
[ "python", "regex" ]
Using regex, extract quoted strings that may contain nested quotes
39,638,172
<p>I have the following string:</p> <pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' </code></pre> <p>Now, I wish to extract the following quotes:</p> <pre ...
2
2016-09-22T11:47:43Z
39,640,166
<p>It seems difficult to achieve with juste one regex pass, but it could be done with a relatively simple regex and a recursive function:</p> <pre><code>import re REGEX = re.compile(r"(['\"])(.*?[!.,])\1", re.S) S = """'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied...
0
2016-09-22T13:16:30Z
[ "python", "regex" ]
Using regex, extract quoted strings that may contain nested quotes
39,638,172
<p>I have the following string:</p> <pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' </code></pre> <p>Now, I wish to extract the following quotes:</p> <pre ...
2
2016-09-22T11:47:43Z
39,704,186
<p><strong>EDIT</strong></p> <p>I modified my regex, it match properly even more complicated cases:</p> <pre><code>(?=(?&lt;!\w|[!?.])('|\")(?!\s)(?P&lt;content&gt;(?:.(?!(?&lt;=(?=\1).)(?!\w)))*)\1(?!\w)) </code></pre> <p><a href="https://regex101.com/r/Q0t3Rp/1" rel="nofollow">DEMO</a></p> <p>It is now even more ...
1
2016-09-26T13:26:53Z
[ "python", "regex" ]
Using regex, extract quoted strings that may contain nested quotes
39,638,172
<p>I have the following string:</p> <pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' </code></pre> <p>Now, I wish to extract the following quotes:</p> <pre ...
2
2016-09-22T11:47:43Z
39,706,568
<p>If you <em>really</em> need to return all the results from a single regular expression applied only once, it will be necessary to use lookahead (<code>(?=findme)</code>) so the finding position goes back to the start after each match - see <a href="http://stackoverflow.com/questions/869809/combine-regexp#870506">thi...
2
2016-09-26T15:18:43Z
[ "python", "regex" ]
Using regex, extract quoted strings that may contain nested quotes
39,638,172
<p>I have the following string:</p> <pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' </code></pre> <p>Now, I wish to extract the following quotes:</p> <pre ...
2
2016-09-22T11:47:43Z
39,729,281
<p>This is a great question for Python regex because sadly, in my opinion the <code>re</code> module is <a href="http://www.rexegg.com/regex-python.html#missing_in_re" rel="nofollow">one of the most underpowered of mainstream regex engines</a>. That's why for any serious regex work in Python, I turn to Matthew Barnett'...
1
2016-09-27T15:59:09Z
[ "python", "regex" ]
Replacing nodal values in a mesh with >1e6 inputs selectively using a polygon
39,638,189
<p>I have a set of data which represents a set of nodes, each node is associated with a value (represented by a color in the image). What I want to achieve is selectively changing those values.</p> <p>The mesh represents a porous system (say a rock for example) model. The pressure in my system is specified at the node...
0
2016-09-22T11:48:15Z
39,641,942
<p>I'm trying to answer, but not sure if this will suffice:</p> <p>You can save a list creation by replacing this part in <code>edit_values</code>:</p> <pre><code>for n,point in enumerate(points): if inPoly(poly, point, True): value = str(get_point_weighted_value(poly, point)) new_pair.append([val...
1
2016-09-22T14:32:13Z
[ "python", "performance", "python-2.7", "optimization", "geometry" ]
How to print words (and punctuation) from a list of positions
39,638,306
<p>(Removed Code to stop Class mates copying) Right now it will create a text file with positions of each word, so for example if I wrote</p> <p>"Hello, my name is mika, Hello" </p> <p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it ...
-1
2016-09-22T11:52:39Z
39,638,466
<pre><code>indices = [1,2,3,4,5,6,2,1] namelst = ['Hello', ',', 'my', 'name', 'is', 'mika'] newstr = " ".join([namelst[x-1] for x in indices]) print (newstr) </code></pre> <p>output:</p> <pre><code>&gt;&gt; 'Hello , my name is mika , Hello' </code></pre> <p>I agree there will be some offsets / spaces, but it will g...
0
2016-09-22T12:00:03Z
[ "python", "list" ]
How to print words (and punctuation) from a list of positions
39,638,306
<p>(Removed Code to stop Class mates copying) Right now it will create a text file with positions of each word, so for example if I wrote</p> <p>"Hello, my name is mika, Hello" </p> <p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it ...
-1
2016-09-22T11:52:39Z
39,638,740
<p><strong>Code:</strong> (Will remove spaces after punctuation)</p> <pre><code>postitions = [1,2,3,4,5,6,2,1] wordslist = ['Hello', ',', 'my', 'name', 'is', 'mika'] recreated='' for i in indices: w = namelst[i-1] if w not in ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]: w = ' ' + w ...
0
2016-09-22T12:12:16Z
[ "python", "list" ]
How to print words (and punctuation) from a list of positions
39,638,306
<p>(Removed Code to stop Class mates copying) Right now it will create a text file with positions of each word, so for example if I wrote</p> <p>"Hello, my name is mika, Hello" </p> <p>The positions in that list would be [1,2,3,4,5,6,2,1], and it will also list each word/punctuation but only once, so in this case it ...
-1
2016-09-22T11:52:39Z
39,638,837
<p>You can use <code>numpy</code> to do this.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; indices = np.array([1,2,3,4,5,6,2,1]) &gt;&gt;&gt; namelst = np.array(['Hello', ',', 'my', 'name', 'is', 'mika', ',', 'Hello']) &gt;&gt;&gt; ' '.join(namelst[indices-1]) 'Hello , my name is mika , Hello' </code></...
0
2016-09-22T12:16:51Z
[ "python", "list" ]
Convert entries of an array to a list
39,638,324
<p>I have numpy arrays which entries consists of either zeros or ones. For example <code>A = [ 0. 0. 0. 0.]</code>, <code>B= [ 0. 0. 0. 1.]</code>, <code>C= [ 0. 0. 1. 0.]</code> Now I want to convert them into a list: <code>L =['0000', '0001', '0010']</code>. Is there an easy way to do it?</p>
0
2016-09-22T11:53:38Z
39,638,764
<p>You can convert each list to a string using <code>join</code> like this</p> <pre><code>def join_list(x): return ''.join([str(int(i)) for i in x]) A = [0, 0, 0, 0] B = [0, 0, 0, 1] C = [0, 0, 1, 0] print(join_list(A)) # 0000 </code></pre> <p>The you can add them all to a new list with a <code>for</code> loop<...
1
2016-09-22T12:13:35Z
[ "python", "arrays", "list" ]
Convert entries of an array to a list
39,638,324
<p>I have numpy arrays which entries consists of either zeros or ones. For example <code>A = [ 0. 0. 0. 0.]</code>, <code>B= [ 0. 0. 0. 1.]</code>, <code>C= [ 0. 0. 1. 0.]</code> Now I want to convert them into a list: <code>L =['0000', '0001', '0010']</code>. Is there an easy way to do it?</p>
0
2016-09-22T11:53:38Z
39,638,877
<p>You need to cast to <code>str(int(ele))</code> and then join:</p> <pre><code>["".join([str(int(f)) for f in arr]) for arr in (A, B, C)] </code></pre> <p>Or since you seem to have numpy arrays:</p> <pre><code>["".join(map(str, arr.astype(int))) for arr in (A,B,C)] </code></pre> <p>Or use astype twice:</p> <pre><...
1
2016-09-22T12:19:10Z
[ "python", "arrays", "list" ]
Raising my own Exception in Python 2.7
39,638,400
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p> <pre><code>def inputNumber (): x = input ('Pick a number: ') if x == 17: raise 'BadNumberError', '17 is a bad number' return x inputNumber() </code></pre> <p>This ...
0
2016-09-22T11:56:51Z
39,638,450
<p>You should be raising exceptions as raise as follows <code>BadNumberError('17 is a bad number')</code> if you have already defined <code>BadNumberError</code> class exception.</p> <p>If you haven't, then</p> <pre><code>class BadNumberError(Exception): pass </code></pre> <p>And here is the <a href="https://doc...
0
2016-09-22T11:59:18Z
[ "python" ]
Raising my own Exception in Python 2.7
39,638,400
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p> <pre><code>def inputNumber (): x = input ('Pick a number: ') if x == 17: raise 'BadNumberError', '17 is a bad number' return x inputNumber() </code></pre> <p>This ...
0
2016-09-22T11:56:51Z
39,638,486
<p>Just inherit from <code>Exception</code> class, then you can throw your own exceptions:</p> <pre><code>class BadNumberException(Exception): pass raise BadNumberException('17 is a bad number') </code></pre> <p>output:</p> <pre><code>Traceback (most recent call last): File "&lt;module1&gt;", line 4, in &lt;m...
0
2016-09-22T12:01:09Z
[ "python" ]
Raising my own Exception in Python 2.7
39,638,400
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p> <pre><code>def inputNumber (): x = input ('Pick a number: ') if x == 17: raise 'BadNumberError', '17 is a bad number' return x inputNumber() </code></pre> <p>This ...
0
2016-09-22T11:56:51Z
39,638,489
<p>If you want to define a <a href="https://docs.python.org/2/tutorial/errors.html#user-defined-exceptions" rel="nofollow">your own error</a> you have to do:</p> <pre><code>class BadNumberError(Exception): pass </code></pre> <p>and then use it:</p> <pre><code>def inputNumber (): x = input ('Pick a number: ')...
0
2016-09-22T12:01:17Z
[ "python" ]
Raising my own Exception in Python 2.7
39,638,400
<p>I copied and pasted these lines of code from a Pyhton tutorial book. Why does this code not work when I try to run it in PyCharm?</p> <pre><code>def inputNumber (): x = input ('Pick a number: ') if x == 17: raise 'BadNumberError', '17 is a bad number' return x inputNumber() </code></pre> <p>This ...
0
2016-09-22T11:56:51Z
39,638,537
<p>You can use standard exceptions:</p> <pre><code>raise ValueError('17 is a bad number') </code></pre> <p>Or you can define your own:</p> <pre><code>class BadNumberError(Exception): pass </code></pre> <p>And then use it:</p> <pre><code>raise BadNumberError('17 is a bad number') </code></pre>
2
2016-09-22T12:02:57Z
[ "python" ]
ValueError: cannot use inplace with CategoricalIndex
39,638,403
<p>I am using <strong>pandas 0.18</strong>.</p> <p>This fails </p> <pre><code> cat_fields[f[0]].add_categories(s,inplace=True) </code></pre> <p>However the <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.Series.cat.add_categories.html#pandas.Series.cat.add_categories" rel="nofollow">docs</...
0
2016-09-22T11:57:00Z
39,638,446
<p>I think you need assign to original column, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cat.add_categories.html" rel="nofollow"><code>Series.add_categories</code></a> has <code>inplace</code> parameter and it works nice.</p> <p>But in <a href="http://pandas.pydata.org/pandas...
0
2016-09-22T11:59:01Z
[ "python", "pandas", "add", "categorical-data", "in-place" ]
What's The Mapping Reduction Function
39,638,679
<p>This is (I think) easy problem from Complexity Theory. </p> <pre><code>#Consider the language E over the binary alphabet #consisting of strings representing even non-negative #integers (with leading zeros allowed). #I.e. E = {x | x[-1] == '0'}. # #Reduce E to the language {'Even'} by implementing #the function R ...
0
2016-09-22T12:09:25Z
39,639,102
<p>So basically you have <code>E</code> as the binary representations of integers, even numbers only. This is indicated by the last digit (integer 1) being <code>0</code>. All other digits represent multiples of 2 and therefore do not matter.</p> <p>The target "language" consists just of the string <code>"Even"</code>...
0
2016-09-22T12:29:23Z
[ "python", "complexity-theory", "turing-machines" ]
PyQT4: why does QDialog returns from exec_() when setVisible(false)
39,638,749
<p>I'm using Python 2.7 and PyQT4.</p> <p>I want to hide a modal QDialog instance and later on show it again. However, when dialog.setVisible(false) is called (e.g., using QTimer), the dialog.exec_() call returns (with QDialog.Rejected return value).</p> <p>However, according to <a href="http://pyqt.sourceforge.net/D...
1
2016-09-22T12:12:53Z
39,640,634
<p>In case anyone is interested, the following code provides a quick-and-dirty way to circunvent the problem for me, although it does not really answer the question.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """Extension of the QDialog class so that exec_() does not exit when hidden. Dialogs inheri...
0
2016-09-22T13:36:31Z
[ "python", "pyqt", "pyqt4" ]
PyQT4: why does QDialog returns from exec_() when setVisible(false)
39,638,749
<p>I'm using Python 2.7 and PyQT4.</p> <p>I want to hide a modal QDialog instance and later on show it again. However, when dialog.setVisible(false) is called (e.g., using QTimer), the dialog.exec_() call returns (with QDialog.Rejected return value).</p> <p>However, according to <a href="http://pyqt.sourceforge.net/D...
1
2016-09-22T12:12:53Z
39,644,737
<p>You can bypass the normal behaviour of <code>QDialog.setVisible</code> (which implicitly closes the dialog), by calling the base-class method instead:</p> <pre><code> def hide_dialog(self): # self.dialog.setVisible(False) QtGui.QWidget.setVisible(self.dialog, False) </code></pre> <p>However, it ...
3
2016-09-22T16:52:20Z
[ "python", "pyqt", "pyqt4" ]
how to apply filter on one variable considering other two variable using python
39,638,777
<p>I am having data with variables <code>participants</code>, <code>origin</code>, and <code>score</code>. And I want those participants and origin whose score is <code>greater than 60</code>. That means to filter participants I have to consider origin and score. I can filter only on origin or only on score but it will...
2
2016-09-22T12:14:00Z
39,638,824
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>df = pd.DataFrame({'participants':['a','s','d'], 'origin':['f','g','t'], 'score':[7,80,9]}) print (df) or...
2
2016-09-22T12:16:27Z
[ "python", "pandas", "indexing", "condition", "tableau" ]
Loop over groups Pandas Dataframe and get sum/count
39,638,801
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/PQ6lS.png" rel="nofollow"><img src="http://i.stack.imgur.com/PQ6lS.png" alt="DataFrame"></a></p> <p>And this is the code which enabled me to get this DataFrame:</p> <pre><code>(data[['time_bucket', 'beg...
0
2016-09-22T12:15:13Z
39,640,134
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, but need same levels of <code>indexes</code> of both <code>DataFrames</code>, so use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.ht...
1
2016-09-22T13:14:52Z
[ "python", "pandas", "dataframe", "count", "sum" ]
Aggregate dataframe indices in python
39,638,833
<p>I want to aggregate indices of a dataframe with groupby function. </p> <pre><code> word count 0 a 3 1 the 5 2 a 3 3 an 2 4 the 1 </code></pre> <p>What I want is a pd.Series which consists of list(descending order) of indices,</p> <pre><code>word a [2, 0] an [3] th...
1
2016-09-22T12:16:44Z
39,638,881
<p>I think you can first change order of <code>index</code> by <code>[::-1]</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and <code>apply</code> <code>index</code> to <code>list</code>. Last <a href="http://pandas.pydat...
2
2016-09-22T12:19:25Z
[ "python", "pandas", "series" ]
recv_pyobj behaves different from Thread to Process
39,638,835
<p><br> I am trying to read data from sockets on 6 different proceses at a time for perfomance sake. I made a test with opening 6 threads and do a socket read from each one and another test with opening 6 sub-processes and read a different socket. Thread reading works fine and it looks like this: </p> <pre><code>class...
0
2016-09-22T12:16:48Z
39,640,540
<p>Actually, the problem was because of the passing SOCKET type argument to a Process/Thread. It seems that pickling, behind the scenes that serializes the data passed to callback method does not serialize well the SOCKET argument. <br> So, I changed it so I would not pass a socket argument:</p> <pre><code>context = z...
0
2016-09-22T13:32:46Z
[ "python", "multithreading", "sockets", "subprocess" ]
redis.exceptions.ConnectionError after approximately one day celery running
39,638,839
<p>This is my full trace:</p> <pre><code> Traceback (most recent call last): File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packages/celery/app/trace.py", line 283, in trace_task uuid, retval, SUCCESS, request=task_request, File "/home/propars/propars-v2-backend/venv/lib/python3.4/site-packa...
0
2016-09-22T12:16:59Z
39,639,598
<p>Have you enabled the rdb background save method in redis ??<br/> if so check for the size of the <code>dump.rdb</code> file in <code>/var/lib/redis</code>.<br/> Sometimes the file grows in size and fill the <code>root</code> directory and the redis instance cannot save to that file anymore.</p> <p>You can stop the ...
0
2016-09-22T12:51:11Z
[ "python", "django", "redis", "celery", "redis-py" ]
What happens when I loop a dict in python
39,638,897
<p>I know <code>Python</code> will simply return the key list when I put a <code>dict</code> in <code>for...in...</code> syntax.</p> <p>But what what happens to the dict?</p> <p>When we use <code>help(dict)</code>, we can not see <code>__next()__</code> method in the method list. So if I want to make a derived class ...
1
2016-09-22T12:20:09Z
39,639,173
<p>Naively, if all you want is for iteration over an instance of <code>MyClass</code> to yield the values instead of the keys, then in <code>MyClass</code> define:</p> <pre><code>def __iter__(self): return self.itervalues() </code></pre> <p>In Python 3:</p> <pre><code>def __iter__(self): return iter(self.val...
0
2016-09-22T12:32:20Z
[ "python", "dictionary" ]
Adding two asynchronous lists, into a dictionary
39,639,035
<p>I've always found Dictionaries to be an odd thing in python. I know it is just me i'm sure but I cant work out how to take two lists and add them to the dict. If both lists were mapable it wouldn't be a problem something like <code>dictionary = dict(zip(list1, list2))</code> would suffice. However, during each run t...
0
2016-09-22T12:26:03Z
39,639,242
<p>Based on your comment all you need is assigning the second list as a value to only item of first list.</p> <pre><code>d = {} d[list1[0]] = list2 </code></pre> <p>And if you want to preserve the values for duplicate keys you can use <code>dict.setdefault()</code> in order to create value of list of list for duplica...
2
2016-09-22T12:35:53Z
[ "python", "dictionary" ]
finding string in a list and return it index or -1
39,639,097
<p>Defining a procedure which return an index of item or -1 if the item not in list</p> <pre><code>def ser(a,b): for j in a: if j == b: return (a.index(b)) else: return -1 print (ser([1,2,3],3)) </code></pre> <p>It's always return me -1. If i cut the 'else' part, it works....
-2
2016-09-22T12:29:10Z
39,639,143
<p>The <code>else</code> block is executed after the first iteration does not fulfill <code>j == b</code>. </p> <p>You're better off moving the else block to the <code>for</code> which executes if the item is not found after the <code>for</code> loop is <em>exhausted</em>:</p> <pre><code>def ser(a,b): for j in a:...
1
2016-09-22T12:31:18Z
[ "python", "list", "indexing" ]
finding string in a list and return it index or -1
39,639,097
<p>Defining a procedure which return an index of item or -1 if the item not in list</p> <pre><code>def ser(a,b): for j in a: if j == b: return (a.index(b)) else: return -1 print (ser([1,2,3],3)) </code></pre> <p>It's always return me -1. If i cut the 'else' part, it works....
-2
2016-09-22T12:29:10Z
39,639,191
<p>That is because the first time you do not match the condition in your loop you immediately return and leave your method. You need to re-think your logic here to determine what it is you want to do when you don't match. Ultimately, you want to continue looping until you have exhausted your checks.</p> <p>So, simply ...
2
2016-09-22T12:33:12Z
[ "python", "list", "indexing" ]
finding string in a list and return it index or -1
39,639,097
<p>Defining a procedure which return an index of item or -1 if the item not in list</p> <pre><code>def ser(a,b): for j in a: if j == b: return (a.index(b)) else: return -1 print (ser([1,2,3],3)) </code></pre> <p>It's always return me -1. If i cut the 'else' part, it works....
-2
2016-09-22T12:29:10Z
39,639,235
<p>In the first iteration of the for loop, it will test if the first element in the array is equal to b. It is not, so the code returns -1 immediately, without testing the other elements of the array.</p> <p>For your case, the correct code is:</p> <pre><code>def ser(a,b): for j in a: if j == b: ...
0
2016-09-22T12:35:39Z
[ "python", "list", "indexing" ]
finding string in a list and return it index or -1
39,639,097
<p>Defining a procedure which return an index of item or -1 if the item not in list</p> <pre><code>def ser(a,b): for j in a: if j == b: return (a.index(b)) else: return -1 print (ser([1,2,3],3)) </code></pre> <p>It's always return me -1. If i cut the 'else' part, it works....
-2
2016-09-22T12:29:10Z
39,639,901
<p>You need not to do anything fancy, simple one-liner will work:</p> <pre><code>def ser(a,b): return a.index(b) if b in a else -1 # Example my_list = [1, 2, 3, 4] ser(my_list, 2) # returns: 1 ser(my_list, 8) # returns: -1 </code></pre>
0
2016-09-22T13:04:01Z
[ "python", "list", "indexing" ]
Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
39,639,127
<p>I'm trying to write an importer for a csv file. Here is a minimal example</p> <pre><code>csv_filepathname="/home/thomas/Downloads/zip.csv" your_djangoproject_home="~/Desktop/Projects/myproject/myproject/" import sys,os,csv sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' ...
0
2016-09-22T12:30:28Z
39,639,198
<p>You need to call <code>django.setup()</code> in your script before you use the ORM to access data.</p> <pre><code>import django sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' django.setup() </code></pre> <p>See <a href="https://docs.djangoproject.com/en/1.10/topics/set...
0
2016-09-22T12:33:38Z
[ "python", "django" ]
Convert pandas dataframe column with xml data to normalised columns?
39,639,160
<p>I have a <code>DataFrame</code> in <code>pandas</code>, one of whose columns is a XML string. What I want to do is create one column for each of the xml nodes with column names in a normalised form. For example,</p> <pre><code> id xmlcolumn 1 &lt;main attr1='abc' attr2='xyz'&gt;&lt;item&gt;&lt;prop1&g...
1
2016-09-22T12:31:59Z
39,656,957
<p>The first step that needs to be done is to convert the XML string to a pandas <code>Series</code> (under the assumption, that there will always be the same amount of columns in the end). So you need a function like:</p> <pre><code>def convert_xml(raw): # some etree xml mangling </code></pre> <p>This can be ach...
0
2016-09-23T09:10:32Z
[ "python", "xml", "pandas", "data-analysis" ]
'None' is not displayed as I expected in Python interactive mode
39,639,342
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p> <pre><code>&gt;&gt;&gt; None &gt;&gt;&gt; print(repr(None)) None &gt;&gt;&gt; </code></pre>
3
2016-09-22T12:40:19Z
39,639,399
<p>It's a deliberate feature. If the python code you run evaluates to exactly <code>None</code> then it is not displayed.</p> <p>This is useful a lot of the time. For example, calling a function with a side effect may be useful, and such functions actually return <code>None</code> but you don't usually want to see the...
3
2016-09-22T12:42:57Z
[ "python" ]
'None' is not displayed as I expected in Python interactive mode
39,639,342
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p> <pre><code>&gt;&gt;&gt; None &gt;&gt;&gt; print(repr(None)) None &gt;&gt;&gt; </code></pre>
3
2016-09-22T12:40:19Z
39,639,575
<p>In Python, a function that does not return anything but is called only for its side effects actually returns None. As such functions are common enough, Python interactive interpreter does not print anything in that case. By extension, it does not print anything when the interactive expression evaluates to None, even...
1
2016-09-22T12:50:18Z
[ "python" ]
'None' is not displayed as I expected in Python interactive mode
39,639,342
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p> <pre><code>&gt;&gt;&gt; None &gt;&gt;&gt; print(repr(None)) None &gt;&gt;&gt; </code></pre>
3
2016-09-22T12:40:19Z
39,639,637
<p><a href="https://docs.python.org/3/library/constants.html#None" rel="nofollow"><code>None</code></a> represents the absence of a value, but that absence can be observed. Because it represents <em>something</em> in Python, its <code>__repr__</code> cannot possibly return <em>nothing</em>; <code>None</code> is not not...
1
2016-09-22T12:52:56Z
[ "python" ]
'None' is not displayed as I expected in Python interactive mode
39,639,342
<p>I thought the display in Python interactive mode was always equivalent to <code>print(repr())</code>, but this is not so for <code>None</code>. Is this a language feature or am I missing something? Thank you</p> <pre><code>&gt;&gt;&gt; None &gt;&gt;&gt; print(repr(None)) None &gt;&gt;&gt; </code></pre>
3
2016-09-22T12:40:19Z
39,641,065
<p>Yes, this behaviour is intentional.</p> <p>From the <a href="https://docs.python.org/3/reference/simple_stmts.html#expression-statements" rel="nofollow">Python docs</a></p> <blockquote> <p>7.1. Expression statements</p> <p>Expression statements are used (mostly interactively) to compute and write a value,...
2
2016-09-22T13:54:52Z
[ "python" ]
Drawing a rubberband on a panel without redrawing everthing in wxpython
39,639,497
<p>I use a wx.PaintDC() to draw shapes on a panel. After drawing the shapes, when I left click and drag mouse, a rubberband (transparent rectangle) is drawn over shapes. While dragging the mouse, for each motion of mouse, an EVT_PAINT is sent and everything (all shapes and rectangle) is redrawn.</p> <p>How do I just d...
0
2016-09-22T12:47:35Z
39,640,694
<p>You presumably want to have a look at <a href="https://wxpython.org/Phoenix/docs/html/wx.Overlay.html?highlight=overlay" rel="nofollow"><code>wx.Overlay</code></a>. Look <a href="https://github.com/wxWidgets/wxPython/blob/master/sandbox/test_Overlay.py" rel="nofollow">here</a> for an example.</p>
2
2016-09-22T13:38:49Z
[ "python", "wxpython" ]
How can i use matplotlib on Anaconda? (Win 7 x64)
39,639,535
<p>I'm using Anaconda on Windows 7 64 bits but i'm unable to use any external package (numpy, matplotlib,scipy). At first when i tried to load this code:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() </code></pre> <p>I got a DLL error. Then, i downloaded and ...
-1
2016-09-22T12:49:04Z
39,641,072
<p>You should try to run the installation without the mkl optimizations.</p> <pre><code>conda remove mkl mkl-service conda install nomkl numpy scipy scikit-learn numexpr </code></pre> <p>edit:</p> <p>Your problem seems to be that you installed the packages from the website and not from the anaconda channels. Clean y...
0
2016-09-22T13:55:06Z
[ "python", "numpy", "matplotlib", "64bit", "anaconda" ]
Scrapy API - Spider class init argument turned to None
39,639,568
<p>After a fresh install of Miniconda 64-bit exe installer for Windows and Python 2.7 on Windows 7, through which I get Scrapy, here is what is installed:</p> <ul> <li>Python 2.7.12</li> <li>Scrapy 1.1.1</li> <li>Twisted 16.4.1</li> </ul> <p>This minimal code, run from "python scrapy_test.py" (using Scrapy API):</p> ...
0
2016-09-22T12:50:05Z
39,646,168
<p>Here is the method definition for <a href="http://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess.crawl" rel="nofollow"><code>scrapy.crawler.CrawlerProcess.crawl()</code></a>:</p> <blockquote> <p><code>crawl(crawler_or_spidercls, *args, **kwargs)</code></p> <ul> <li><strong>crawler_o...
2
2016-09-22T18:17:08Z
[ "python", "scrapy" ]
Memory error on large Shapefile in Python
39,639,579
<pre><code>import shapefile data = shapefile.Reader("data_file.shp") shapes = data.shapes() </code></pre> <p>My problem is that getting the shapes from the Shapefile reader gives me an exception <code>MemoryError</code> when using <a href="https://pypi.python.org/pypi/pyshp" rel="nofollow">Pyshp</a>.</p> <p>The <code...
0
2016-09-22T12:50:24Z
39,639,735
<p>Quoting from <a href="http://stackoverflow.com/questions/5537618/memory-errors-and-list-limits">this answer</a> by thomas:</p> <blockquote> <p>The <code>MemoryError</code> exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit i...
3
2016-09-22T12:57:06Z
[ "python", "shapefile", "pyshp" ]
Memory error on large Shapefile in Python
39,639,579
<pre><code>import shapefile data = shapefile.Reader("data_file.shp") shapes = data.shapes() </code></pre> <p>My problem is that getting the shapes from the Shapefile reader gives me an exception <code>MemoryError</code> when using <a href="https://pypi.python.org/pypi/pyshp" rel="nofollow">Pyshp</a>.</p> <p>The <code...
0
2016-09-22T12:50:24Z
39,649,506
<p>Although I haven't been able to test it, Pyshp should be able to read it regardless of the file size or memory limits. Creating the <code>Reader</code> instance doesn't load the entire file, only the header information. </p> <p>It seems the problem here is that you used the <code>shapes()</code> method, which reads...
1
2016-09-22T21:57:31Z
[ "python", "shapefile", "pyshp" ]
translating RegEx syntax working in php and python to JS
39,639,589
<p>I have this RegEx syntax: "(?&lt;=[a-z])-(?=[a-z])"</p> <p>It captures a dash between 2 lowercase letters. In example below the second dash is captured:</p> <p>Krynica-Zdrój, ul. Uzdro-jowa</p> <p>Unfortunately I can't use &lt;= in JS. My ultimate goal is to remove the hyphen with RegEx replace.</p>
1
2016-09-22T12:50:49Z
39,639,788
<p>It seems to me you need to remove the hyphen in between lowercase letters.</p> <p>Use</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-js lang-js prettyprint-override"><code>var s = "Krynica-Zdrój, ul. Uzdro-...
1
2016-09-22T12:59:19Z
[ "javascript", "php", "python", "regex" ]
Closing a connection with a `with` statement
39,639,594
<p>I want to have a class that represents an IMAP connection and use it with a <code>with</code> statement as follows:</p> <pre><code>class IMAPConnection: def __enter__(self): connection = imaplib.IMAP4_SSL(IMAP_HOST) try: connection.login(MAIL_USERNAME, MAIL_PASS) except imap...
1
2016-09-22T12:51:07Z
39,639,643
<p>You need to implement a <code>__exit__()</code> function within your <code>IMAPConnection</code> class.</p> <p><code>__enter__()</code> function is called before executing the code within the <code>with</code> block where as <code>__exit__()</code> is called while exiting the <code>with</code> block.</p> <p>Below ...
0
2016-09-22T12:53:08Z
[ "python", "imap", "with-statement", "imaplib" ]
Closing a connection with a `with` statement
39,639,594
<p>I want to have a class that represents an IMAP connection and use it with a <code>with</code> statement as follows:</p> <pre><code>class IMAPConnection: def __enter__(self): connection = imaplib.IMAP4_SSL(IMAP_HOST) try: connection.login(MAIL_USERNAME, MAIL_PASS) except imap...
1
2016-09-22T12:51:07Z
39,639,686
<p>You need to store connection in object attributes. Something like this: </p> <pre><code>class IMAPConnection: def __enter__(self): self.connection = imaplib.IMAP4_SSL(IMAP_HOST) try: self.connection.login(MAIL_USERNAME, MAIL_PASS) except imaplib.IMAP4.error: log....
3
2016-09-22T12:54:46Z
[ "python", "imap", "with-statement", "imaplib" ]
Class_weight for SVM classifier in Python
39,639,698
<p>I have a set of parameters to choose the best ones for svm.SVC classifier using GridSearchCV:</p> <pre><code>X=dataset.ix[:, dataset.columns != 'class'] Y=dataset['class'] X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X, Y, test_size=0.5) clf=svm.SVC() params= {'kernel':['linear', 'r...
0
2016-09-22T12:55:33Z
39,640,552
<p><code>'balanced'</code> should be working as you can see in line 51 or 74 <a href="http://sklearn%20utils%20github" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/class_weight.py</a></p> <p>Execute <code>sklearn.__version__</code> to check what version you are running.</p>
0
2016-09-22T13:33:23Z
[ "python", "machine-learning", "scikit-learn", "svm" ]
DRY way to call method if object does not exist, or flag set?
39,639,732
<p>I have a Django database containing Paper objects, and a management command to populate the database. The management command iterates over a list of IDs and scrapes information about each one, and uses this information to populate the database. </p> <p>This command is run each week, and any new IDs are added to the...
0
2016-09-22T12:57:02Z
39,639,828
<p>If you want to do something like</p> <pre><code>obj, created = Paper.objects.update_or_create( name='Paper') </code></pre> <p>There is a <code>update_or_create</code> in Django since 1.7. Take a look into <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create" rel="nofollow">doc...
0
2016-09-22T13:00:59Z
[ "python", "django" ]
DRY way to call method if object does not exist, or flag set?
39,639,732
<p>I have a Django database containing Paper objects, and a management command to populate the database. The management command iterates over a list of IDs and scrapes information about each one, and uses this information to populate the database. </p> <p>This command is run each week, and any new IDs are added to the...
0
2016-09-22T12:57:02Z
39,641,487
<p>You could incapsulate the parsing process into a helper method:</p> <pre><code>def scrape_new_object(self, id, force_update=False): if not force_update: try: Paper.objects.get(id=id) return except Paper.DoesNotExists: pass info = self._scrape_info(id) ...
0
2016-09-22T14:13:50Z
[ "python", "django" ]
Using regroup in Django template
39,639,747
<p>I'm receiving a JSON object that contains many objects and lists of objects etc. In one of those lists is Year list like this:</p> <pre><code>[{'Year': '2015', 'Status': 'NR', 'Month': 'Jan' {'Year': '2014', Status': '', 'Month': 'Jan'}, {'Year': '2015', 'Status': '',Month': 'Feb'}, {'Year': '2014', Status': '', ...
0
2016-09-22T12:57:53Z
39,641,014
<p>docs: <a href="https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup</a></p> <p><code>regroup</code> expects ordered data in the first place. If all the items with same year are consecutive then you will get the de...
2
2016-09-22T13:52:59Z
[ "python", "django", "django-templates" ]
Inserting one item on a matrix
39,639,953
<p>How do I insert a single element into an array on numpy. I know how to insert an entire column or row using the insert and axis parameter. But how do I insert/expand by one.</p> <p>For example, say I have an array:</p> <pre><code>1 1 1 1 1 1 1 1 1 </code></pre> <p>How do I insert 0 (on the same row), say on (1,...
1
2016-09-22T13:06:41Z
39,640,498
<p>I think you should use <code>append()</code> of regular Python arrays (not numpy) Here is a short example</p> <pre><code>A = [[1,1,1], [1,1,1], [1,1,1]] A[1].append(1) </code></pre> <p>The result is</p> <pre><code>[[1, 1, 1], [1, 1, 1, 1], [1, 1, 1]] # like in your example </code></pre> <p>Column...
-1
2016-09-22T13:31:25Z
[ "python", "numpy" ]
Inserting one item on a matrix
39,639,953
<p>How do I insert a single element into an array on numpy. I know how to insert an entire column or row using the insert and axis parameter. But how do I insert/expand by one.</p> <p>For example, say I have an array:</p> <pre><code>1 1 1 1 1 1 1 1 1 </code></pre> <p>How do I insert 0 (on the same row), say on (1,...
1
2016-09-22T13:06:41Z
39,640,688
<p>Numpy has something that <em>looks</em> like ragged arrays, but those are arrays of objects, and probably not what you want. Note the difference in the following:</p> <pre><code>In [27]: np.array([[1, 2], [3]]) Out[27]: array([[1, 2], [3]], dtype=object) In [28]: np.array([[1, 2], [3, 4]]) Out[28]: array([[1, 2], ...
3
2016-09-22T13:38:38Z
[ "python", "numpy" ]
create dynamic fields in WTform in Flask
39,640,024
<p>I want to create different forms in Flask using WTForms and Jinja2. I make a call to mysql, which has the type of field. </p> <p>So i.e. the table could be:</p> <pre><code> form_id | type | key | options | default_value 1 | TextField | title | | test1 ...
1
2016-09-22T13:09:59Z
39,675,444
<h1>Adding fields dynamically</h1> <blockquote> <p>I think best would be to create an empty form and then add fields in a for-loop, however if a form is posted back how can I validate the form if I don't have it defined in a class?</p> </blockquote> <p>Add the fields to the <strong>form class</strong> using <code>s...
1
2016-09-24T10:42:02Z
[ "python", "flask", "wtforms" ]
How to temporarily disable foreign key constraint in django
39,640,037
<p>I have to update a record which have foreign key constraint. i have to assign 0 to the column which is defined as foreign key while updating django don't let me to update record. </p>
1
2016-09-22T13:10:39Z
39,640,286
<p><strong>ForeignKey</strong> is a many-to-one relationship. Requires a positional argument: the class to which the model is related. </p> <p>It must be <strong>Relation</strong> (class) or <strong>Null</strong> (if null allowed). You cannot set 0 (integer) to ForeignKey columnn.</p>
1
2016-09-22T13:22:27Z
[ "python", "django", "django-models" ]
Temporarily disable increment in SQLAlchemy
39,640,078
<p>I am running a Flask application with SQLAlchemy (1.1.0b3) and Postgres.</p> <p>With Flask I provide an API over which the client is able to GET all instances of a type database and POST them again on a clean version of the Flask application, as a way of local backup. When the client posts them again, they should a...
0
2016-09-22T13:12:33Z
39,656,631
<p>After adding an object with a fixed ID, you have to make sure the normal incremental behavior doesn't cause any collisions with future insertions.</p> <p>A possible solution I can think of is to set the next insertion ID to the maximum ID (+1) found in the table. You can do that with the following additions to your...
0
2016-09-23T08:53:13Z
[ "python", "rest", "flask", "sqlalchemy", "auto-increment" ]
elasticsearch python client - work with many nodes - how to work with sniffer
39,640,200
<p>i have one cluster with 2 nodes. </p> <p>i am trying to understand the best practise to connect the nodes, and check failover when there is downtime on one node.</p> <p>from <a href="http://elasticsearch-py.readthedocs.io/en/master/api.html#nodes" rel="nofollow">documentation</a>:</p> <pre><code>es = Elasticsearc...
0
2016-09-22T13:18:03Z
39,640,389
<p>You need to set <code>sniff_timeout</code> to a higher value than the default value (which is 0.1 if memory serves).</p> <p>Try it like this</p> <pre><code>es = Elasticsearch( ['esnode1', 'esnode2'], # sniff before doing anything sniff_on_start=True, # refresh nodes after a node fails to respond ...
0
2016-09-22T13:26:28Z
[ "python", "elasticsearch", "elasticsearch-py" ]
How i can display customer balance on sale orders in odoo?
39,640,232
<p>I want to display <strong>customer balance</strong> in sale orders but don't know how to do that. Also i want to display customer's <strong>credit limit</strong> and <strong>next payment date</strong>. Anybody have idea how i can do that, Thanks in advance...</p>
0
2016-09-22T13:19:59Z
39,646,295
<p>You can add it by related fields as follow.</p> <p><strong>Balance Field :</strong></p> <pre><code>customer_balance = fields.Float(related="partner_id.credit",string="Balance") </code></pre> <p><strong>Credit Limit</strong></p> <pre><code>customer_credit_limit = fields.Float(related="partner_id.credit_limit",str...
1
2016-09-22T18:24:13Z
[ "python", "openerp", "odoo-8" ]
Error while updating document in Elasticsearch
39,640,268
<p>I am trying to update few documents in Elasticsearch.I want to update value of few fields whose mapping type is long.Currently value of those fields is null.</p> <p>Python Script:</p> <pre><code>def dump_random_values(): query = {"size": 2000, "query": {"bool": {"must": [{"term": {"trip_client_id": {"value": ...
1
2016-09-22T13:21:34Z
39,641,641
<p>It was a small mistake that I was doing.When I queried in Elasticsearch and updated the field values,I should have indexed just the "_source",and not the entire document,which contains some extra fields such as "index","took" etc.</p> <p>Hence this should be the code change:</p> <pre><code>def dump_random_values()...
0
2016-09-22T14:20:23Z
[ "python", "elasticsearch" ]
Python: I want to check for the count of the words in the string
39,640,333
<p>I managed to do that but the case I'm struggling with is when I have to consider 'color' equal to 'colour' for all such words and return count accordingly. To do this, I wrote a dictionary of common words with spelling changes in American and GB English for this, but pretty sure this isn't the right approach.</p> <...
1
2016-09-22T13:24:31Z
39,640,514
<p><strong>Step 1:</strong> Create a temporary string and then replace all the words with <code>values</code> of your dict with it's corresponding keys as:</p> <pre><code>&gt;&gt;&gt; temp_string = str(my_string) &gt;&gt;&gt; for k, v in ukus.items(): ... temp_string = temp_string.replace(" {} ".format(v), " {} "....
0
2016-09-22T13:32:00Z
[ "python", "count" ]
Python: I want to check for the count of the words in the string
39,640,333
<p>I managed to do that but the case I'm struggling with is when I have to consider 'color' equal to 'colour' for all such words and return count accordingly. To do this, I wrote a dictionary of common words with spelling changes in American and GB English for this, but pretty sure this isn't the right approach.</p> <...
1
2016-09-22T13:24:31Z
39,710,348
<p>Okay, I think I know enough from your comments to provide this as a solution. The function below allows you to choose either UK or US replacement (it uses US default, but you can of course flip that) and allows for you to either perform minor hygiene on the string.</p> <pre><code>import re ukus={'COLOUR':'COLOR',...
0
2016-09-26T18:58:29Z
[ "python", "count" ]
Django Admin: Numeric field filter
39,640,350
<p>How to create filter for numeric data in Django Admin with range inputs?</p> <p>P.S. Found only this similar question, but here suggest only how to group by concrete ranges and last question activity was 2 years ago.</p> <p><a href="http://stackoverflow.com/questions/4060396/django-admin-how-do-i-filter-on-an-inte...
0
2016-09-22T13:25:01Z
39,641,497
<p><strong>Warning!</strong> Some parts of API from django, mentioned in my answer, are considered internal and may be changed in future releases of django without any notification.</p> <p>Taking that note to your mind, it is actually pretty easy to create your own filter. All you need to do is:</p> <ol> <li>subclass...
1
2016-09-22T14:14:10Z
[ "python", "django", "django-admin" ]
Python Unit Test Dictionary Assert KeyError
39,640,395
<p>I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:</p> <pre><code>def test_dict_keyerror_should_appear(self): my_dict = {'hey': 'world'} self.assertRaises(KeyError, my_dict['some_key'])...
1
2016-09-22T13:26:54Z
39,640,396
<p>To solve this I used a <code>lambda</code> to call the dictionary key to raise the error.</p> <pre><code>def test_dict_keyerror_should_appear(self): my_dict = {'hey': 'world'} self.assertRaises(KeyError, lambda: my_dict['some_key']) </code></pre>
1
2016-09-22T13:26:54Z
[ "python", "python-unittest" ]
Python Unit Test Dictionary Assert KeyError
39,640,395
<p>I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:</p> <pre><code>def test_dict_keyerror_should_appear(self): my_dict = {'hey': 'world'} self.assertRaises(KeyError, my_dict['some_key'])...
1
2016-09-22T13:26:54Z
39,640,548
<p>Another option would be to use <a href="https://docs.python.org/3/library/operator.html#operator.getitem" rel="nofollow"><code>operator.getitem</code></a>:</p> <pre><code>from operator import getitem self.assertRaises(KeyError, getitem, my_dict, 'some_key') </code></pre>
1
2016-09-22T13:33:09Z
[ "python", "python-unittest" ]
Python requests module file
39,640,451
<p>I am using a third party tool which uses a basic python installation but can compile new python modules on its own. All it needs is a .py file which can be compiled. Somehow, I am not able to locate a readily available requests module file which has the python code within it. Is it possible to guide me to any such r...
-1
2016-09-22T13:29:37Z
39,640,641
<p>you could do <code>pip install requests</code></p> <p>If you dont have PIP installed then you can install it from <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a></p> <p>and then can do <code>python get-pip.py</code>to install pip</p> <p>alternatively you coul...
0
2016-09-22T13:36:47Z
[ "python", "python-requests" ]
How do I make text(one letter) fill out a tkinter button?
39,640,537
<p>I have a tic tac toe game I'm trying to put the finishing touches on. Each tile in the game is a button with the letter 'x' or 'o'. But I can't seem to get the letters to fill out the frame. When I change the font size, the buttons bloat out. If I try to set the tile height/weight after setting the font size it does...
-1
2016-09-22T13:32:41Z
39,901,263
<p>I would say there is no way to make characters automatically fill the entire button's space. Consider <code>Canvas</code> objects instead of <code>Button</code>s. There you can easily draw an X (two lines) and an O (circle) with full control over the size and the space between the edge of the canvas and the sign. ...
0
2016-10-06T16:31:15Z
[ "python", "button", "tkinter" ]
Python multiprocessing pool with shared data
39,640,556
<p>I'm attempting to speed up a multivariate fixed-point iteration algorithm using multiprocessing however, I'm running issues dealing with shared data. My solution vector is actually a named dictionary rather than a vector of numbers. Each element of the vector is actually computed using a different formula. At a high...
1
2016-09-22T13:33:25Z
39,640,879
<p>This is happening because the objects you're putting into the <code>estimates</code> <code>DictProxy</code> aren't actually the same objects as those that live in the regular dict. The <code>manager.dict()</code> call returns a <code>DictProxy</code>, which is proxying access to a <code>dict</code> that actually liv...
1
2016-09-22T13:47:31Z
[ "python", "dictionary", "multiprocessing", "shared-memory" ]
Issue trying to read spreadsheet line by line and write to excel (downsample)
39,640,561
<p>I am trying to write some code to downsample a very large excel file. It needs to copy the first 4 lines exactly, then on the 5th line start taking every 40th line. I currently have this</p> <pre><code>import os import string import shutil import datetime folders = os.listdir('./') names = [s for s in folders if "...
0
2016-09-22T13:33:43Z
39,640,638
<p>You're overwriting the file on each iteration of the previous file. Move that <code>open(...)</code> out of the <code>for</code> loop:</p> <pre><code>with open(filename) as f, open('./DownSampled/' + folder + '.csv', 'w') as f_out: for i, line in enumerate(f): if i &lt; 5: f_out.write(li...
1
2016-09-22T13:36:40Z
[ "python", "excel" ]
python logistic regression - patsy design matrix and categorical data
39,640,672
<p>Quite new to python and machine learning. </p> <p>I am trying to build a logistic regression model. I have worked in R to gain lambda and used cross-validation to find the best model and am now moving it into python. </p> <p>Here I have created a design matrix and made it sparse. Then ran the logistic regression....
0
2016-09-22T13:37:59Z
39,641,281
<p>First I will fix an error with your code and then I will answer your question.</p> <p>Your code: Your <code>train_model</code> function won't return what you think it returns. Currently, it doesn't return anything, and you want it to return both your model and the training score. When you fit a model, you need to d...
0
2016-09-22T14:03:45Z
[ "python", "scikit-learn", "patsy" ]
Django, tutorial - error: No module named urls
39,640,718
<p>Hi I am following the tutorial to make first web app by Django(<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">link</a>) But I was given this error:</p> <pre><code> File "c:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*a...
1
2016-09-22T13:39:58Z
39,640,968
<p>Basic question, but in the settings.py file, do you have <code>polls</code> defined inside the <code>INSTALLED_APPS setting?</code></p>
-2
2016-09-22T13:51:23Z
[ "python", "django" ]
Django, tutorial - error: No module named urls
39,640,718
<p>Hi I am following the tutorial to make first web app by Django(<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">link</a>) But I was given this error:</p> <pre><code> File "c:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*a...
1
2016-09-22T13:39:58Z
39,641,026
<p><code>url(r'^polls/', include('polls.urls'))</code></p> <p>What this line is doing is it's adding the <code>urls.py</code> of <code>polls</code> app folder, to your urls and also appending <code>polls/</code> in front of all.</p> <p><strong>Coming to the error :</strong> </p> <pre><code>File "c:\Python27\Proj\mys...
2
2016-09-22T13:53:23Z
[ "python", "django" ]