title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How can I check if a tar file can be written to using the tarfile module?
38,336,014
<p>I'm looking to append to a .tar file using <code>tarfile</code> but I don't know if the file is in use or not. How can I check to see if the file can be appended to?</p> <p>I've tried:</p> <pre><code>try: with tarfile.open("foo.tar", "a:") as tar: tar.add("bar.txt") except tarfile.TarError: print "erro...
1
2016-07-12T18:03:31Z
38,336,826
<p>The <em>only</em> safe way to do this is:</p> <ul> <li>Make a copy of the file.</li> <li>Open the <em>copy</em> in append mode.</li> <li>Rename the copy over the original.</li> </ul>
2
2016-07-12T18:53:40Z
[ "python", "tar", "tarfile" ]
I don't understand why I get a 'None' in my ouput when running the program
38,336,031
<p>So this is my code:</p> <pre><code>import csv particle_counter = file('C:/Users/Desktop/Level 2 files/HiSAM1_data_160206_134230.csv','rU') gas_csv = file('C:/Users/Desktop/Level 2 files/gas_0.csv','rU') gps_csv = file('C:/Users/Desktop/Level 2 files/gps_0.csv','rU') pm2_5_csv = file('C:/Users/Desktop/Level 2 file...
0
2016-07-12T18:04:19Z
38,336,062
<p><code>skipline()</code> returned it, and you printed it. And <code>skipline()</code> returned it because your <code>while</code> test can never be <code>True</code>:</p> <pre><code>while x &lt; n in filename: </code></pre> <p>The expression <code>x &lt; n in filename</code> is a <em>chained comparison</em>, and is...
3
2016-07-12T18:06:27Z
[ "python", "csv", "header" ]
I don't understand why I get a 'None' in my ouput when running the program
38,336,031
<p>So this is my code:</p> <pre><code>import csv particle_counter = file('C:/Users/Desktop/Level 2 files/HiSAM1_data_160206_134230.csv','rU') gas_csv = file('C:/Users/Desktop/Level 2 files/gas_0.csv','rU') gps_csv = file('C:/Users/Desktop/Level 2 files/gps_0.csv','rU') pm2_5_csv = file('C:/Users/Desktop/Level 2 file...
0
2016-07-12T18:04:19Z
38,336,082
<p>In the <code>skipline()</code> function:</p> <pre><code>def skipline(n,filename): x =0 while x &lt; n in filename: reader = csv.reader(filename) result = next(reader) return result </code></pre> <p><code>x = 0</code> and <code>n = 0</code>. So nothing is being parsed as <code>x &lt;...
0
2016-07-12T18:07:49Z
[ "python", "csv", "header" ]
I'm trying to write a function that will output string a string from a multi-dimensional dictionary.
38,336,040
<p>Here's the function that I wrote: </p> <pre><code>def print_dict(d, indent, CMD_str, index = 0): if isinstance(d,dict): for key, value in d.items(): CMD_str += ('\t' * indent + str(key) + '\n') # print('\t' * indent + str(key) + '\n') if isinstance(value, dict): CMD_str += p...
0
2016-07-12T18:04:59Z
38,336,529
<p>You have some duplicate code in your recursive function that could be reorganized for clarity and to lessen the chances of a bug occurring. Here is an example:</p> <pre><code>tab = " " def print_dict(d, indent): result = [] for key, value in d.items(): result.append(tab*indent + str(key)) ...
0
2016-07-12T18:36:51Z
[ "python", "recursion" ]
I'm trying to write a function that will output string a string from a multi-dimensional dictionary.
38,336,040
<p>Here's the function that I wrote: </p> <pre><code>def print_dict(d, indent, CMD_str, index = 0): if isinstance(d,dict): for key, value in d.items(): CMD_str += ('\t' * indent + str(key) + '\n') # print('\t' * indent + str(key) + '\n') if isinstance(value, dict): CMD_str += p...
0
2016-07-12T18:04:59Z
38,336,899
<ol> <li>Be aware of <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow">pprint</a>.</li> <li>Separate work by scopes - your function does some work itself and expects caller to do the same work too, which leads to code duplication. I've reworked your code a bit:</li> </ol> <hr> <pre><code>from num...
0
2016-07-12T18:59:05Z
[ "python", "recursion" ]
using Python2 library in Python3/Django1.8 web app
38,336,079
<p>I'm trying to use <a href="https://pypi.python.org/pypi/SecureSubmit" rel="nofollow">this SDK/API</a>, but it's built for Python2 and I'm working in a Django 1.8.8 / Python 3.5.1 site. I'm sure I could trigger a Python2 script from Python3-Django, but is it safe to pass secure, web-submitted information to it? Is th...
1
2016-07-12T18:07:18Z
38,486,873
<p>I think it's great you grasped the nettle, I am sure all who use your work will appreciate the ability to use python 3 with this. I am happy to have inspired you to try. </p>
0
2016-07-20T17:16:59Z
[ "python", "django", "credit-card" ]
Mocking a global variable
38,336,090
<p>I've been trying to implement some unit tests for a module. An example module named <em>alphabet.py</em> is as follows:</p> <pre><code>import database def length_letters(): return len(letters) def contains_letter(letter): return True if letter in letters else False letters = database.get('letters') # ...
1
2016-07-12T18:08:14Z
38,336,231
<p>You don't need to use mock. Just import the module and alter the value of the global within <code>setUp()</code>:</p> <pre><code>import alphabet class TestAlphabet(unittest.TestCase): def setUp(self): alphabet.letters = ['a', 'b', 'c'] </code></pre>
1
2016-07-12T18:16:46Z
[ "python", "unit-testing", "mocking", "patch" ]
Mocking a global variable
38,336,090
<p>I've been trying to implement some unit tests for a module. An example module named <em>alphabet.py</em> is as follows:</p> <pre><code>import database def length_letters(): return len(letters) def contains_letter(letter): return True if letter in letters else False letters = database.get('letters') # ...
1
2016-07-12T18:08:14Z
38,336,234
<p>Try this:</p> <pre><code>import unittests import alphabet from unittest.mock import patch class TestAlphabet(unittest.TestCase): def setUp(self): self.mock_letters = mock.patch.object( alphabet, 'letters', return_value=['a', 'b', 'c'] ) def test_length_letters(self): ...
0
2016-07-12T18:17:02Z
[ "python", "unit-testing", "mocking", "patch" ]
Running fabric script throws ImportError: No module named fabric.main
38,336,154
<p>I am on Redhat, and when I run any fabric scripts I see the following error:</p> <blockquote> <p>Traceback (most recent call last): File "/usr/bin/fab", line 8, in from fabric.main import main ImportError: No module named fabric.main</p> </blockquote> <p>The file /usr/bin/fab is configured to use pyth...
0
2016-07-12T18:11:33Z
38,358,380
<p>I ended up doing the following:</p> <ol> <li><p>Install Python 2.7 in a virtualenv (<code>~/virtualenvs/py2.7</code>) by following the top-rated answer from <a href="http://stackoverflow.com/questions/5506110/is-it-possible-to-install-another-version-of-python-to-virtualenv">Is it possible to install another versio...
0
2016-07-13T17:39:48Z
[ "python", "python-2.7", "redhat", "fabric", "importerror" ]
reading numy array from GCS into spark
38,336,197
<p>I have 100 npz files containing numpy arrays in google storage. I have setup dataproc with jupyter and I am trying to read all the numpy arrays into spark RDD. What is the best way to load the numpy arrays from a google storage into pyspark? Is there an easy way like <code>np.load("gs://path/to/array.npz")</code> t...
1
2016-07-12T18:14:26Z
38,336,843
<p>If you plan to scale eventually you'll want to use the distributed input methods in <code>SparkContext</code> rather than doing any local file loading from the driver program relying on <code>sc.parallelize</code>. It sounds like you need to read each of the files intact though, so in your case you want:</p> <pre><...
2
2016-07-12T18:54:45Z
[ "python", "google-cloud-storage", "pyspark", "google-cloud-dataproc" ]
Using multithreading for a function with a while loop?
38,336,217
<p>I have a pretty basic function that iters through a directory, reading files and collecting data, however it does this way too slow and only uses about a quarter of each core (quad-core i5 CPU) for processing power. How can I run the function 4 times simultaneously. Because it's going through a rather large director...
1
2016-07-12T18:16:08Z
38,336,439
<p>This method <code>pool.map(function)</code> will create 4 threads, not actually 4 processes. All this "multiprocessing" will happen in the same process with 4 threads.</p> <p>What I suggest is to use the <code>multiprocessing.Process</code> according the documentation <a href="https://docs.python.org/2/library/mult...
-2
2016-07-12T18:29:32Z
[ "python", "multithreading", "multiprocessing" ]
Using multithreading for a function with a while loop?
38,336,217
<p>I have a pretty basic function that iters through a directory, reading files and collecting data, however it does this way too slow and only uses about a quarter of each core (quad-core i5 CPU) for processing power. How can I run the function 4 times simultaneously. Because it's going through a rather large director...
1
2016-07-12T18:16:08Z
38,336,457
<p>I didn't use <code>map()</code>, it is said map takes only one iterable argument, theoretically, you either modify your <code>fuction()</code> to <code>function(one_arg)</code> or try to use an empty list or tuple or other iterable structure but I didn't test it. </p> <p>I suggest you put all files into queue(can b...
3
2016-07-12T18:30:57Z
[ "python", "multithreading", "multiprocessing" ]
Rewriting .csv data to file creates artifacted first column in python
38,336,278
<p>I'm taking data in csv from multiple REST endpoints, trying to add column headers to the data, and change the delimiters in the data from semicolons (;) to commas (,) so they can be formatted correctly by excel.</p> <p>For note: x in the code below is a list of the link URIs and the ellipsis replaces the code used ...
1
2016-07-12T18:20:08Z
38,336,607
<p>Manually adding <code>,</code> to the file will cause column alignment problems as the manually inserted <code>,</code>s will clash with the ones inserted by the <code>csv.writer</code> as delimiter.</p> <p>Changing the delimiter from <code>;</code> to <code>,</code> will not require an extra <code>replace(";", ","...
1
2016-07-12T18:41:42Z
[ "python", "python-3.x", "csv" ]
Python sqlite3 order error
38,336,307
<p>So, I am trying to understand this:</p> <pre><code> c.execute('SELECT * FROM random ORDER BY id') line = c.fetchall() for row in line: text.insert(END, row) text.insert(END, '\n') </code></pre> <p>With the Sqlite3 list:</p> <pre><code>1 7 2 94 3 15 </code></pre> <p>(The first number ...
0
2016-07-12T18:21:36Z
38,336,339
<p>Looks like the column <code>id</code> is of type <code>char</code>, so the order is correct, because the string <code>11</code> is lower than 2. You should change the type of column id to <code>int</code> or you have to conver id before ordering</p>
2
2016-07-12T18:23:41Z
[ "python", "sqlite3" ]
Python sqlite3 order error
38,336,307
<p>So, I am trying to understand this:</p> <pre><code> c.execute('SELECT * FROM random ORDER BY id') line = c.fetchall() for row in line: text.insert(END, row) text.insert(END, '\n') </code></pre> <p>With the Sqlite3 list:</p> <pre><code>1 7 2 94 3 15 </code></pre> <p>(The first number ...
0
2016-07-12T18:21:36Z
38,336,357
<p>In your output you have quotes around 11: <code>'11'</code> -- it means it is a string of 11. Somehow, you need to make sure you store integers in id field.</p>
2
2016-07-12T18:24:56Z
[ "python", "sqlite3" ]
How to avoid this redundancy when using Django model inheritance?
38,336,324
<p>All pages in my Django website have a footer link "Feedback/Questions". If the new person comes to the site and clicks that link, they should be directed to a form with a pulldown to indicate if they have feedback versus a question and fields for their email address and their feedback or question. The page will ha...
2
2016-07-12T18:22:23Z
38,336,638
<p>I wouldn't subclass your models - if it's an anonymous question you could just include a <code>user</code> attribute as well as an <code>email</code> attribute on one model with <code>blank=True</code> and <code>null=True</code>:</p> <pre><code>class FeedbackQuestion(models.Model): submission_type = ... (type,...
1
2016-07-12T18:43:55Z
[ "python", "django", "inheritance", "django-models" ]
How to use multiple background colors for a figure in Python?
38,336,372
<p>I just want to plot several data sets, say 4, using subfigures, i.e. something like</p> <pre><code>fig = figure(1) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) </code></pre> <p>This is working well. But additionally I´d like to set different backgroun...
2
2016-07-12T18:25:41Z
38,471,332
<p>I had the same problem and came up with the following solution:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure(1) # create rectangles for the background upper_bg = patches.Rectangle((0, 0.5), width=1, height=0.5, transform=fig.tra...
1
2016-07-20T02:27:37Z
[ "python", "background-color", "figure", "subfigure" ]
matplotlib.pyplot.scatter() loses color when importing seaborn package?
38,336,383
<p>I am working on generating some scatter plot with <code>matplotlib.pyplot.scatter()</code> in jupyter notebook, and I found that if I import <code>seaborn</code> package, the scatter plot will lose its color. I am wondering if anyone has a similar issue?</p> <p>Here is an example code</p> <pre><code>import matplo...
1
2016-07-12T18:26:12Z
38,336,900
<p>That seems to be the way it behaves. In seaborn 0.3 the default color scale was changed to greyscale. If you change your code to:</p> <p><code>plt.scatter(range(4),range(4), c=sb.color_palette())</code></p> <p>You will get an image with colors similar to your original. See the Seaborn docs on <a href="https://sta...
1
2016-07-12T18:59:06Z
[ "python", "matplotlib", "plot" ]
matplotlib.pyplot.scatter() loses color when importing seaborn package?
38,336,383
<p>I am working on generating some scatter plot with <code>matplotlib.pyplot.scatter()</code> in jupyter notebook, and I found that if I import <code>seaborn</code> package, the scatter plot will lose its color. I am wondering if anyone has a similar issue?</p> <p>Here is an example code</p> <pre><code>import matplo...
1
2016-07-12T18:26:12Z
38,404,120
<p>Another way to fix this is to specify <code>cmap</code> option for <code>plt.scatter()</code> so that it would not be affected by <code>seaborn</code>:</p> <pre><code>ax = plt.scatter(range(4),range(4), c=range(4), cmap='gist_rainbow') plt.colorbar(ax) </code></pre> <p>The result is: <a href="http://i.stack.imgur....
1
2016-07-15T19:52:41Z
[ "python", "matplotlib", "plot" ]
RemovedInDjango110Warning: The context_instance argument of render_to_string is deprecated
38,336,440
<p>For one of the apps, I'm overloading the "delete selected objects" method in a Django 1.9.x project which uses the Admin panel. For that, I have a code similar to this:</p> <pre><code>from django.contrib.admin import helpers from django.http import HttpResponseRedirect from django.shortcuts import render_to_respons...
0
2016-07-12T18:29:38Z
38,336,563
<p>Yes, the "right" way to fix it would be to update it. According to the <a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#id1" rel="nofollow">documentation, they recommend using <code>render()</code></a></p> <blockquote> <p>Deprecated since version 1.8: The context_instance argument is deprec...
2
2016-07-12T18:39:04Z
[ "python", "django", "django-templates", "django-admin" ]
I cant get my labels to change automaticaly with Kivy
38,336,463
<p>I am new to programming and have been trying to make this project with the Raspberry Pi for over a year now. The problem is I can't seem to get my labels to change automatically. I've tried Clock.schedule_interval but it does nothing. Maybe I've been trying in the wrong place?</p> <p><strong>main.py</strong></p> <...
0
2016-07-12T18:31:28Z
38,336,958
<p>You need to make outtemp and currtemp as StringProperty()</p> <p>Like this:</p> <pre><code>from kivy.properties import StringProperty class MainWidget(Widget): outtemp = StringProperty() currtemp = StringProperty() </code></pre> <p>Make sure the functions return strings</p> <pre><code>return str(temper...
0
2016-07-12T19:02:36Z
[ "python", "kivy" ]
NameError after attempt to apply imported modules
38,336,485
<p>I have a slightly lengthy and repetitive program where I import other modules into it to then put in all the information gathered together into a completed sentence. The issue I am having is everything I had defined before moving onto the next part, shows up as a NameError.</p> <p>Here's the code:</p> <pre><code> ...
-1
2016-07-12T18:33:36Z
38,337,348
<p>It's because when you import something, variables don't carry over. Instead, you should say this:</p> <pre><code>def place(): print("As a reminder, I am unable to tell the difference between places and anything else you respond with. You can make me sound silly, or you can just answer the question so everything...
1
2016-07-12T19:25:41Z
[ "python", "import", "nameerror" ]
NameError after attempt to apply imported modules
38,336,485
<p>I have a slightly lengthy and repetitive program where I import other modules into it to then put in all the information gathered together into a completed sentence. The issue I am having is everything I had defined before moving onto the next part, shows up as a NameError.</p> <p>Here's the code:</p> <pre><code> ...
-1
2016-07-12T18:33:36Z
38,337,358
<p>I'd convert your "modules" to functions, and put them all within the same module (this really isn't a very big program, nor any reason I see to have separate modules for this). Then, you can run this module and the entire program will run as intended:</p> <pre><code>def GetNameAge(): print("Hello! \nWhat is you...
0
2016-07-12T19:26:15Z
[ "python", "import", "nameerror" ]
Create a ranking for user
38,336,493
<p>I have many users on my DB</p> <pre><code>User -- Points user1 4 user2 6 user3 2 user4 3 user5 8 user6 9 user7 1 user8 5 </code></pre> <p>I'm looking for the easiest and with less errors way to create a 5 rank for specific user. Where the user I choose should be in the middle and have 2 on top and ...
-1
2016-07-12T18:34:10Z
38,336,990
<p><del>I make it on sql server but work same on postgresql.</del> I include both now.</p> <ul> <li>check <a href="https://www.postgresql.org/docs/9.5/static/tutorial-window.html" rel="nofollow"><strong>Rank()</strong></a> function, and see how handle ties or use <code>row_number()</code></li> <li>use a variable inste...
1
2016-07-12T19:04:09Z
[ "python", "django", "postgresql", "django-rest-framework" ]
Create a ranking for user
38,336,493
<p>I have many users on my DB</p> <pre><code>User -- Points user1 4 user2 6 user3 2 user4 3 user5 8 user6 9 user7 1 user8 5 </code></pre> <p>I'm looking for the easiest and with less errors way to create a 5 rank for specific user. Where the user I choose should be in the middle and have 2 on top and ...
-1
2016-07-12T18:34:10Z
38,337,230
<p>here <code>t5</code> is your table and <code>u</code> is column with users and <code>r</code> is column with points... I tried with user value of 'u4' - try with yours...</p> <pre><code>select u,r from ( select *, case when l2 = 'u4' or r1 &gt; 0 or r &lt; max(ur) over () then 1 else 0 end r2 from ( select *, case ...
0
2016-07-12T19:18:16Z
[ "python", "django", "postgresql", "django-rest-framework" ]
Remove All Commas Between Quotes
38,336,518
<p>I'm trying to remove all commas that are inside quotes (<code>"</code>) with python:</p> <pre><code>'please,remove all the commas between quotes,"like in here, here, here!"' ^ ^ </code></pre> <p>I tried this, but it only removes the first comma inside t...
4
2016-07-12T18:36:06Z
38,336,655
<p>Assuming you don't have unbalanced or escaped quotes, you can use this regex based on negative lookahead:</p> <pre><code>&gt;&gt;&gt; str = r'foo,bar,"foobar, barfoo, foobarfoobar"' &gt;&gt;&gt; re.sub(r'(?!(([^"]*"){2})*[^"]*$),', '', str) 'foo,bar,"foobar barfoo foobarfoobar"' </code></pre> <p>This regex will fi...
6
2016-07-12T18:44:44Z
[ "python", "regex" ]
Remove All Commas Between Quotes
38,336,518
<p>I'm trying to remove all commas that are inside quotes (<code>"</code>) with python:</p> <pre><code>'please,remove all the commas between quotes,"like in here, here, here!"' ^ ^ </code></pre> <p>I tried this, but it only removes the first comma inside t...
4
2016-07-12T18:36:06Z
38,336,669
<p>You can pass a function as the <code>repl</code> argument instead of a replacement string. Just get the entire quoted string and do a simple string replace on the commas.</p> <pre><code>&gt;&gt;&gt; s = 'foo,bar,"foobar, barfoo, foobarfoobar"' &gt;&gt;&gt; re.sub(r'"[^"]*"', lambda m: m.group(0).replace(',', ''), ...
3
2016-07-12T18:45:33Z
[ "python", "regex" ]
Remove All Commas Between Quotes
38,336,518
<p>I'm trying to remove all commas that are inside quotes (<code>"</code>) with python:</p> <pre><code>'please,remove all the commas between quotes,"like in here, here, here!"' ^ ^ </code></pre> <p>I tried this, but it only removes the first comma inside t...
4
2016-07-12T18:36:06Z
38,336,735
<p>What about doing it with out regex?</p> <pre><code>input_str = '...' first_slice = input_str.split('"') second_slice = [first_slice[0]] for slc in first_slice[1:]: second_slice.extend(slc.split(',')) result = ''.join(second_slice) </code></pre>
0
2016-07-12T18:49:00Z
[ "python", "regex" ]
Remove All Commas Between Quotes
38,336,518
<p>I'm trying to remove all commas that are inside quotes (<code>"</code>) with python:</p> <pre><code>'please,remove all the commas between quotes,"like in here, here, here!"' ^ ^ </code></pre> <p>I tried this, but it only removes the first comma inside t...
4
2016-07-12T18:36:06Z
38,337,775
<p>Here is another option I came up with if you don't want to use regex.</p> <pre><code>input_str = 'please,remove all the commas between quotes,"like in here, here, here!"' quotes = False def noCommas(string): quotes = False output = '' for char in string: if char == '"': quotes = Tr...
1
2016-07-12T19:52:31Z
[ "python", "regex" ]
Heroku "failed to compile" with heroku/python build pack, with no signs of pip running
38,336,537
<p>I am developing a Python app using <code>aiohttp</code> and <code>redis</code> to run in Heroku. It is deployed to Heroku via GitHub. Although there is no problem running the app locally, it fails to build in Heroku with the following error.</p> <pre><code>-----&gt; Using set buildpack heroku/python -----&gt; Pytho...
0
2016-07-12T18:37:23Z
38,777,354
<p>Ok. So I had the same issue as you did. If you look closely you see:</p> <pre><code>Requested runtime (python-3.5.2 </code></pre> <p>Notice the "(". Probably has something to do with the encoding of the file. In Ubuntu I used dos2unix (apt-get install dos2unix &amp;&amp; dos2unix runtime.txt) which solved this iss...
0
2016-08-04T21:01:04Z
[ "python", "heroku", "deployment" ]
Find first ReGex pattern following a different pattern
38,336,593
<p><strong>Objective:</strong> find a second pattern and consider it a match only if it is the first time the pattern was seen following a different pattern.</p> <p><strong>Background:</strong></p> <p>I am using Python-2.7 Regex</p> <p>I have a specific Regex match that I am having trouble with. I am trying to get t...
0
2016-07-12T18:40:46Z
38,336,739
<p>Not sure if I understand your problem correctly, but <code>re.findall('Sample comments:[^\\[]*\\[([^\\]]*)\\]', string)</code> seems to work.</p> <p>Or maybe <code>re.findall('Sample comments:[^\\[]*\\[[ \t]*([^\\]]*?)[ \t]*\\]', string)</code> if you want to strip the final spaces from your line?</p>
0
2016-07-12T18:49:11Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
Find first ReGex pattern following a different pattern
38,336,593
<p><strong>Objective:</strong> find a second pattern and consider it a match only if it is the first time the pattern was seen following a different pattern.</p> <p><strong>Background:</strong></p> <p>I am using Python-2.7 Regex</p> <p>I have a specific Regex match that I am having trouble with. I am trying to get t...
0
2016-07-12T18:40:46Z
38,336,745
<p>I suggest using</p> <pre><code>r'Sample comments:\s*\[(.*?)\s*]' </code></pre> <p>See the <a href="https://regex101.com/r/rH4kS1/1" rel="nofollow">regex</a> and <a href="http://ideone.com/FZ5Ee0" rel="nofollow">IDEONE demo</a></p> <p>The point is the <code>\s*</code> matches zero or more whitespace, both vertica...
3
2016-07-12T18:49:41Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
Format a pandas dataframe
38,336,649
<pre><code> MachineName EventLogs 0 P79 Yes 1 P14 Yes 2 P1 No 3 P93 No </code></pre> <p>I count the number of logs in a dataframe using the below statement:</p> <pre><code>df1 = pd.value_counts(df['Logs'].values, sort=False) </code></pre> <p>and when I print <code>df1</cod...
1
2016-07-12T18:44:37Z
38,336,709
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, because you have <code>Series</code>:</p> <pre><code>df1 = pd.value_counts(df['Logs'].values, sort=False).reset_index() df1.columns = ['value','count'] </code></pre...
1
2016-07-12T18:47:17Z
[ "python", "pandas", "matplotlib", "dataframe", "pie-chart" ]
Format a pandas dataframe
38,336,649
<pre><code> MachineName EventLogs 0 P79 Yes 1 P14 Yes 2 P1 No 3 P93 No </code></pre> <p>I count the number of logs in a dataframe using the below statement:</p> <pre><code>df1 = pd.value_counts(df['Logs'].values, sort=False) </code></pre> <p>and when I print <code>df1</cod...
1
2016-07-12T18:44:37Z
38,336,742
<p>I don't know what you're using to make your pie charts, but pandas has some perfectly reasonable plotting capabilities (through matplotlib).</p> <p><code>df1.plot(kind='pie')</code></p>
0
2016-07-12T18:49:24Z
[ "python", "pandas", "matplotlib", "dataframe", "pie-chart" ]
regex and python
38,336,727
<p>I have a string:</p> <pre><code>myString = "123ABC,'2009-12-23T23:45:58.544-04:00'" </code></pre> <p>I want to extract the "T" character from the Timestamp, ie change it to: </p> <pre><code>"123ABC,'2009-12-23 23:45:58.544-04:00'" </code></pre> <p>I am trying this: </p> <pre><code>newString = re.sub('(?:\-\d{2}...
-1
2016-07-12T18:48:33Z
38,336,758
<p><code>regex</code> seems a bit of an overkill:</p> <pre><code>mystring.replace("T"," ") </code></pre>
1
2016-07-12T18:50:10Z
[ "python", "regex" ]
regex and python
38,336,727
<p>I have a string:</p> <pre><code>myString = "123ABC,'2009-12-23T23:45:58.544-04:00'" </code></pre> <p>I want to extract the "T" character from the Timestamp, ie change it to: </p> <pre><code>"123ABC,'2009-12-23 23:45:58.544-04:00'" </code></pre> <p>I am trying this: </p> <pre><code>newString = re.sub('(?:\-\d{2}...
-1
2016-07-12T18:48:33Z
38,336,771
<p>You can use lookarounds (<em>positive lookbehind and -ahead</em>):</p> <pre><code>(?&lt;=\d)T(?=\d) </code></pre> <p>See <a href="https://regex101.com/r/wR4mA3/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>. <hr> In <code>Python</code> this would be:</p> <pre><code>import re myString = "123ABC,'200...
2
2016-07-12T18:51:01Z
[ "python", "regex" ]
regex and python
38,336,727
<p>I have a string:</p> <pre><code>myString = "123ABC,'2009-12-23T23:45:58.544-04:00'" </code></pre> <p>I want to extract the "T" character from the Timestamp, ie change it to: </p> <pre><code>"123ABC,'2009-12-23 23:45:58.544-04:00'" </code></pre> <p>I am trying this: </p> <pre><code>newString = re.sub('(?:\-\d{2}...
-1
2016-07-12T18:48:33Z
38,336,865
<p>I'd use capturing groups, unanchored lookbehinds are costly in terms of regex performance:</p> <pre><code>(\d)T(\d) </code></pre> <p>And replace with <code>r'\1 \2'</code> replacement pattern containing backreferences to the digit before and after <code>T</code>. See the <a href="https://regex101.com/r/sP5mR1/1" r...
0
2016-07-12T18:56:27Z
[ "python", "regex" ]
regex and python
38,336,727
<p>I have a string:</p> <pre><code>myString = "123ABC,'2009-12-23T23:45:58.544-04:00'" </code></pre> <p>I want to extract the "T" character from the Timestamp, ie change it to: </p> <pre><code>"123ABC,'2009-12-23 23:45:58.544-04:00'" </code></pre> <p>I am trying this: </p> <pre><code>newString = re.sub('(?:\-\d{2}...
-1
2016-07-12T18:48:33Z
38,336,891
<p>That <code>T</code> is trapped in between numbers and will always be alone on the right. You could use a <code>rsplit</code> and <code>join</code>:</p> <pre><code>myString = "123ABC,'2009-12-23T23:45:58.544-04:00'" s = ' '.join(myString.rsplit('T', maxsplit=1)) print(s) # "123ABC,'2009-12-23 23:45:58.544-04:00'" </...
0
2016-07-12T18:58:45Z
[ "python", "regex" ]
How to replace a function call in an existing method
38,336,814
<p>given a module with a class Foo with a method that calls a function <code>bar</code> defined in the module scope, is there a way to substitute <code>bar</code> for a different function without modification to the module?</p> <pre><code>class Foo(object): def run(self): bar() def bar(): return True ...
3
2016-07-12T18:53:12Z
38,336,854
<p>Let's assume your module is called <code>deadbeef</code>, and you're using it like this</p> <pre><code>import deadbeef … foo_instance = deadbeef.Foo() </code></pre> <p>Then you could do </p> <pre><code>import deadbeef deadbeef.bar = baz … </code></pre>
7
2016-07-12T18:55:33Z
[ "python", "monkeypatching" ]
How to replace a function call in an existing method
38,336,814
<p>given a module with a class Foo with a method that calls a function <code>bar</code> defined in the module scope, is there a way to substitute <code>bar</code> for a different function without modification to the module?</p> <pre><code>class Foo(object): def run(self): bar() def bar(): return True ...
3
2016-07-12T18:53:12Z
38,336,901
<p>You can monkey patch <code>Foo</code> at run time, and override the method <code>run</code>.</p> <p>For example if <code>foo</code> is instance of <code>Foo</code> you can do:</p> <pre><code>def run(obj): baz() foo.run = run </code></pre> <p>Next time you call <code>foo.run</code> it will invoke <code>baz</...
4
2016-07-12T18:59:19Z
[ "python", "monkeypatching" ]
How to replace a function call in an existing method
38,336,814
<p>given a module with a class Foo with a method that calls a function <code>bar</code> defined in the module scope, is there a way to substitute <code>bar</code> for a different function without modification to the module?</p> <pre><code>class Foo(object): def run(self): bar() def bar(): return True ...
3
2016-07-12T18:53:12Z
38,337,846
<p>I asked something similar recently and <strong>staticmethod</strong> was the answer (because your baz and bar dont seem to be methods). Basically, you want to do something like the Strategy Pattern and call a different function from run().</p> <pre><code>def bar(): print "I am bar()" return True def baz()...
0
2016-07-12T19:57:53Z
[ "python", "monkeypatching" ]
How to build a dictionary in Python based on my list?
38,336,938
<p>I have a simple list </p> <pre><code>a = ["one", "two", "three"] </code></pre> <p>and I am trying to build something similar to this:</p> <pre><code>[ { "key": "foo", "value": "one" }, { "key": "foo", "value": "two" }, { "key": "foo", "value": "...
-2
2016-07-12T19:01:35Z
38,336,981
<p>A simple comprehension</p> <pre><code>[{"key": "foo", "value": v} for v in ["one", "two", "three"]] </code></pre> <p>But you probably want something more like</p> <pre><code>[{"foo": v} for v in ["one", "two", "three"]] </code></pre> <p>which gives you</p> <pre><code>In [11]: [{"foo": v} for v in ["one", "two",...
1
2016-07-12T19:03:37Z
[ "python" ]
How can I change the colour of an unordered list that has an unknown depth and is generated recursively?
38,336,952
<p>I have a dictionary:</p> <pre><code>tree['node-A'] = { 'class-type': 'Date' 'class-type-index': 0 } tree['node-B'] = { 'class-type': 'Ratio' 'class-type-index': 1 } tree['node-C'] = { 'class-type': 'Integer' 'class-type-index': 2 } </code></pre> <p>And in the HTML I generate the classe...
1
2016-07-12T19:02:16Z
38,341,614
<p>I supposed that exists a depth limit, so you can use a simple 'for' to generate the css like this:</p> <pre><code>$class: "index"; $base-color: green; $depth-limit: 5; @for $i from 0 through $depth-limit { .#{$class}-#{$i} { background-color: darken($base-color, 5 * $i); } } </code></pre>
1
2016-07-13T02:17:02Z
[ "python", "html", "css", "sass" ]
Bottle Server not working on Centos
38,336,972
<p>I wrote a bottle application on windows and moved it to a centos server that is also running an apache web server. I have bottle running: </p> <pre><code>Bottle v0.12.9 server starting up (using GeventServer())... Listening on http://127.0.0.1:8080/ Hit Ctrl-C to quit. </code></pre> <p>Whenever I try to send a req...
0
2016-07-12T19:03:19Z
38,708,058
<p>This is not how bottle works, If your code looks like this example:</p> <pre><code>import bottle @bottle.route("/hello") def func(): return "hello!!!!!!!" if __name__ == "__main__": bottle.run(port=8080) </code></pre> <p>Then browse to <a href="http://127.0.0.1:8080/hello" rel="nofollow">http://127.0.0.1...
0
2016-08-01T21:02:09Z
[ "python", "apache", "bottle" ]
Returning Functions or Values: recursive python functions
38,337,034
<p>Would anyone be willing to explain why the first does not work, but the second does? </p> <p>In the first, the function calculates the final, adjusted value...</p> <pre><code># returns None def _pareRotation(degs): if degs &gt; 360: _pareRotation(degs - 360) else: print "returnin...
0
2016-07-12T19:06:58Z
38,337,052
<p>You're not <em>returning</em> in the first case:</p> <pre><code>def _pareRotation(degs): if degs &gt; 360: _pareRotation(degs - 360) # ^ </code></pre>
4
2016-07-12T19:08:30Z
[ "python", "recursion" ]
Returning Functions or Values: recursive python functions
38,337,034
<p>Would anyone be willing to explain why the first does not work, but the second does? </p> <p>In the first, the function calculates the final, adjusted value...</p> <pre><code># returns None def _pareRotation(degs): if degs &gt; 360: _pareRotation(degs - 360) else: print "returnin...
0
2016-07-12T19:06:58Z
38,337,091
<p>Yeah, you aren't returning in the first case, and also I think it should be %d, for int.</p>
0
2016-07-12T19:10:35Z
[ "python", "recursion" ]
NoReverseMatch, why django doesn't find the url?
38,337,141
<p>I've a little problem with my urls and I searched for some times but didnt found a correct answer.</p> <p>I get the following error:</p> <pre><code>NoReverseMatch at /base/teams/ Reverse for 'base-home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p>Here is my ur...
0
2016-07-12T19:13:47Z
38,337,186
<p>That would be because this line</p> <pre><code>url(r'^base/$', include('django.contrib.flatpages.urls'), name='base-home'), </code></pre> <p>doesn't actually resolve to a view. Instead it is an <code>include</code> statement.</p> <p>See <a href="http://stackoverflow.com/questions/1144691/how-can-i-get-the-reverse...
1
2016-07-12T19:16:21Z
[ "python", "django" ]
Capitalization of filenames storing Python classes
38,337,150
<p><strong>C++</strong></p> <p>I use a rigorous rule of capitalizing class names.</p> <p>Over many years I tried to use the somewhat inconsistent rule of using lowercase names for the files—when writing in C++.</p> <p>For example, <code>class Stopwatch</code> would be in the files <code>stopwatch.hpp</code> and <c...
0
2016-07-12T19:14:26Z
38,337,240
<p>In python each file is a module so to follow PEP8 your code should be as follows</p> <pre><code>from stopwatch import Stopwatch </code></pre> <p>Therefore the file should be stopwatch.py</p>
4
2016-07-12T19:19:01Z
[ "python", "pep" ]
How to pass an HttpResponse and additional data via Ajax in Django
38,337,342
<p>I have two different AJAX requests that I want to combine.</p> <p>The first one gets some html:</p> <pre><code>def ajax_get_html(request): if request.is_ajax() and request.method == "POST": context = { ... } return render(request,"my_app/my_template.html", context) else:...
1
2016-07-12T19:25:16Z
38,338,944
<p>You can't serialize the output of Django's <code>render</code> because it <a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render" rel="nofollow">returns an HttpResponse object</a>, not a string (which is what you want to be able to serialize it).</p> <p>A good solution is to return your html t...
1
2016-07-12T21:10:42Z
[ "python", "json", "ajax", "django", "django-views" ]
Proper way to split a text and append it into an array
38,337,391
<p>I am getting stuck with the following code:</p> <pre><code>fname = raw_input("Enter file name: ") fh = open(fname).readlines() lst = list() for line in fh: line.rstrip() w_list = line.split() for word in w_list: if word not in lst: lst.append(word) </code></pre> <p>I gue...
-2
2016-07-12T19:28:26Z
38,338,762
<p>You don't need to use <code>readlines()</code>. Python makes things a lot easier. Try this:</p> <pre><code>f = open('myfile.txt', 'r') #set option modes lst = [] for line in f: inner_words = line.rstrip().split() for word in inner_words: if not word in lst: lst.append(word) </code></pre>...
0
2016-07-12T20:57:57Z
[ "python", "split", "append" ]
Python Nested For Loop CSV File
38,337,414
<p>This code only iterates through the number of rows once I would like to iterate through all the rows for the number of columns in the data I'm confused as to why it isn't iterating through the rows 7 times.</p> <pre><code>import csv from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt imp...
2
2016-07-12T19:29:21Z
38,337,487
<p>Your code has a outer loop that will loop 7 times, and the inner loop will loop over each row. You need to swap the inner and outer loops. </p> <p>For each row loop over each column </p> <pre><code>with open('test3.csv') as csvfile: readCsv = csv.reader(csvfile, delimiter =',') for row in readCsv: ...
1
2016-07-12T19:33:59Z
[ "python", "python-3.x", "csv", "matplotlib" ]
Python Nested For Loop CSV File
38,337,414
<p>This code only iterates through the number of rows once I would like to iterate through all the rows for the number of columns in the data I'm confused as to why it isn't iterating through the rows 7 times.</p> <pre><code>import csv from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt imp...
2
2016-07-12T19:29:21Z
38,337,517
<p>Once you read all the rows in the file, the file data is exhausted and there's nothing left to read, so your <code>for row in readCsv:</code> loop immediately terminates.</p> <p>If you want to reset the file and read it all over again, you'll need to close the file and open it again.</p>
0
2016-07-12T19:35:24Z
[ "python", "python-3.x", "csv", "matplotlib" ]
Python Nested For Loop CSV File
38,337,414
<p>This code only iterates through the number of rows once I would like to iterate through all the rows for the number of columns in the data I'm confused as to why it isn't iterating through the rows 7 times.</p> <pre><code>import csv from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt imp...
2
2016-07-12T19:29:21Z
38,337,518
<p>Similar question here: <a href="http://stackoverflow.com/questions/2868354/reading-from-csvs-in-python-repeatedly">Reading from CSVs in Python repeatedly?</a></p> <p>After you loop through the file, you need to reset the read position of csvfile. </p> <pre><code> csvfile.seek(0) </code></pre>
0
2016-07-12T19:35:28Z
[ "python", "python-3.x", "csv", "matplotlib" ]
virtualenv dependent on where you start python from
38,337,425
<p>I'm normally a unix/Mac person, so I'm not exactly sure how this might be related, but one of my users is on a windows box (windows 7?) running via cmd command line.</p> <p>I have a virtualenv set up for windows, on this one system (other computers work fine) I can start the virtualenv (activate.bat) and when I run...
-1
2016-07-12T19:30:00Z
38,340,169
<p>Apparently the problem is that my code and the virtualenv live on dropbox. which means that it gets copied to each new computer. The fact that it worked in powershell on a 2nd computer was just a fluke... Now I need to figure out a better way to do this in the first place... <em>sigh</em></p>
0
2016-07-12T23:03:09Z
[ "python", "windows", "python-venv" ]
Firebase Cloud Messaging InvalidRegistration for Topic Messages
38,337,540
<p>I am having trouble sending a topic downstream message using Firebase. Everything works fine when I send to single or multiples users using tokens, my code looks like this</p> <pre><code>notif = { 'to': 'TOKEN', 'data': {'msg': 'whatever'}, } opener = urllib2.build_opener() data = json.dumps(notif) req = ur...
2
2016-07-12T19:36:45Z
38,337,829
<p>Ah so silly...</p> <p>I was missing <strong>s</strong> in topics, the correct form is hence</p> <pre><code>notif = { 'to': '/topics/MY_TOPIC', 'data': {'msg': 'whatever'}, } </code></pre> <p>Hope it helps someone anyway!</p> <p>Best, A</p>
2
2016-07-12T19:56:48Z
[ "python", "firebase", "google-cloud-messaging", "firebase-cloud-messaging" ]
Python error "io.UnsupportedOperation: write" when writing UTF-8 Characters
38,337,627
<p>I am using python 3.5.2 interpreter in a Windows 10 environment. </p> <p>I entered the following lines according to the Google's Python Course:</p> <pre><code>&gt;&gt;&gt; import sys,os,codecs &gt;&gt;&gt; f=codecs.open('foo.txt','rU','utf-8') &gt;&gt;&gt; for line in f: ... f.write('£ $') ... Traceback (most ...
-1
2016-07-12T19:43:25Z
38,337,715
<p>You have the file open for reading, not writing. Hence, the unsupported operation. You can't write to a file opened for reading.</p> <p>The <code>rU</code> specified reading</p> <pre><code>f=codecs.open('foo.txt','rU','utf-8') </code></pre> <p>To open for writing:</p> <pre><code>f=codecs.open('foo.txt','w','utf-...
0
2016-07-12T19:49:01Z
[ "python", "utf-8", "ansi" ]
Concatenating fields of a feature class using python without field calculator
38,337,756
<p>This seems like it should be relatively straightforward, but I have not been able to get it to work.</p> <p>I have a feature class within which I would like to concatenate attributes. I would like to combine a county identification field (county FIPS code) with a unique identifier field that I generated. I would l...
0
2016-07-12T19:51:53Z
38,402,523
<p>I hope I'm understanding your question correctly here:</p> <p>In python, it should come out looking something like this: </p> <pre><code>arcpy.CalculateField_management(TableX, "final_id", "!unique_id! + !id_num! ", "PYTHON_9.3", "") </code></pre> <p>As a general rule, a good method for getting 'vetted' python c...
0
2016-07-15T18:01:53Z
[ "python", "field", "concatenation", "arcgis", "string-concatenation" ]
How do I count the number of times a term has occured in the values of a list of JSON objects?
38,337,789
<p>I am working on a Python code where I need to put a check on the assignment of a value to a key in a JSON object on the basis of user input. My approach is to create a check using the if-statement on the number of times of the occurrence of the specific key value, for that I need to count the number of times that sp...
1
2016-07-12T19:54:04Z
38,338,313
<p>Could you do</p> <pre><code>sum((1 for v in json.loads("...") if v.get("territory") == abc)) </code></pre>
2
2016-07-12T20:27:30Z
[ "python", "json" ]
Can an IPython/Jupyter notebook cell be imported as if it were a module?
38,337,792
<p>Is there a means in IPython to <code>import</code> the contents of a notebook cell as if it were a separate module? Or alternatively get the contents of a cell to have its own namespace.</p>
3
2016-07-12T19:54:21Z
39,063,663
<p>@Mike, as mentioned in the comment you can follow the well documented steps in the following link to import a Jupyter Notebook as a module:</p> <p><a href="http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html" rel="nofollow">Importing Jupyter Notebooks as Modules</a></p> <p...
1
2016-08-21T11:27:08Z
[ "python", "ipython", "ipython-notebook", "jupyter-notebook" ]
Zipline: where are the .pickle files saved?
38,337,802
<p>I'm a beginner to zipline and I have been trying to run the example here given in the QuickStart:</p> <p><a href="https://github.com/quantopian/zipline" rel="nofollow">https://github.com/quantopian/zipline</a></p> <p>I was able to get this command to run on my mac in terminal:</p> <pre><code>python run_algo.py -f...
0
2016-07-12T19:54:50Z
38,631,548
<p>I figured out that the parameters for output should not be <code>-o</code>.</p> <p>It should be <code>-output</code>.</p> <p>So this will output the pickle:</p> <pre><code>python -f dual_moving_average.py --start 2011-1-1 --end 2012-1-1 -output dma.pickle </code></pre>
0
2016-07-28T08:56:04Z
[ "python", "osx", "zipline" ]
Is there a scipy/numpy alternative to R's nrd0?
38,337,804
<p>From the <a href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/bandwidth.html" rel="nofollow">R Documentation</a>...</p> <blockquote> <p>bw.nrd0 implements a rule-of-thumb for choosing the bandwidth of a Gaussian kernel density estimator. It defaults to 0.9 times the minimum of the standard deviat...
2
2016-07-12T19:55:01Z
38,337,911
<p>If you are working with KDE's can you just use scipy.stats.gaussian_kde? It implements Silverman's and Scott's rules for bandwidth selection.</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.s...
-1
2016-07-12T20:01:30Z
[ "python", "numpy", "scipy" ]
Is there a scipy/numpy alternative to R's nrd0?
38,337,804
<p>From the <a href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/bandwidth.html" rel="nofollow">R Documentation</a>...</p> <blockquote> <p>bw.nrd0 implements a rule-of-thumb for choosing the bandwidth of a Gaussian kernel density estimator. It defaults to 0.9 times the minimum of the standard deviat...
2
2016-07-12T19:55:01Z
38,338,353
<p>The precedence of operators in an English sentence is ambiguous.</p> <p>Here's an implementation that returns the value you expect:</p> <pre><code>In [201]: x = np.arange(1, 401) In [202]: 0.9*min(np.std(x, ddof=1), (np.percentile(x, 75) - np.percentile(x, 25))/1.349)*len(x)**(-0.2) Out[202]: 31.393668650034652 <...
3
2016-07-12T20:30:03Z
[ "python", "numpy", "scipy" ]
Is there a scipy/numpy alternative to R's nrd0?
38,337,804
<p>From the <a href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/bandwidth.html" rel="nofollow">R Documentation</a>...</p> <blockquote> <p>bw.nrd0 implements a rule-of-thumb for choosing the bandwidth of a Gaussian kernel density estimator. It defaults to 0.9 times the minimum of the standard deviat...
2
2016-07-12T19:55:01Z
38,338,389
<p>You don't have the right calculation for IQR:</p> <pre><code>import numpy def bw_nrd0(x): if len(x) &lt; 2: raise(Exception("need at least 2 data points")) hi = numpy.std(x, ddof=1) q75, q25 = numpy.percentile(x, [75 ,25]) iqr = q75 - q25 lo = min(hi, iqr/1.34) if not ((lo == hi)...
2
2016-07-12T20:32:37Z
[ "python", "numpy", "scipy" ]
Is there a difference between dumpdata and simply piping the output to a file?
38,337,810
<p>In the <a href="https://docs.djangoproject.com/en/1.9/ref/django-admin/#dumpdata" rel="nofollow">docs</a>, you can see that by using <code>manage.py dumpdata -o file.json</code>, it will dump your database to <code>file.json</code>. However, without a <code>-o</code> flag specified, it simply outputs the dump to sta...
0
2016-07-12T19:55:19Z
38,339,210
<p>There shouldn't be any difference between <code>manage.py dumpdata &gt; file.json</code> and <code>./manage.py dumpdata -o file.json</code>, apart from the progress bar.</p> <p>If you do <code>manage.py dumpdata &gt;&gt; file.json</code> then that will <em>append</em> the output to <code>file.json</code>.</p>
0
2016-07-12T21:31:02Z
[ "python", "django" ]
Iterating through all pixels, if within range, change pixel to black, else to white
38,337,872
<p>So basically, i want to iterate over all my pixels, and if they are withing range, change their RGB values to white, else to black.</p> <p>I've seen a couple of examples where a mask is used, but i'm a ittle confused as to how i would use a mask to compare an RGB value. My range is as such</p> <pre><code>min_YCrCb...
0
2016-07-12T19:59:41Z
38,338,970
<p>I think the <a href="http://opencv.itseez.com/2.4/modules/core/doc/operations_on_arrays.html?highlight=inrange#cv2.inRange" rel="nofollow">inRange</a> method is what you need.</p> <p>So, in your example you could use:</p> <pre><code># Keep in mind that OpenCV stores things in BGR order, not RGB lowerBound = cv.Sca...
0
2016-07-12T21:12:33Z
[ "python", "opencv", "pixel", "mask" ]
Replace list value in Python dictionary
38,337,955
<p>I have the following dictionary. For objects that have the value <code>['FAIL', 'PASS']</code>, I'd like to replace it with <code>'PASS'</code> only.</p> <pre><code>Dict = [('Main Menu-046', ['PASS']), ('Main Menu-047', ['FAIL']), ('Main Menu-044', ['FAIL', 'PASS']), ('Main Menu-045', ['PASS']), ('Main Menu-042', [...
0
2016-07-12T20:04:16Z
38,338,076
<p>If I understood your question correctly, you want to replace <code>['FAIL', 'PASS']</code> with <code>['PASS']</code></p> <pre><code>processed_list = [(x[0], ["PASS"] if "PASS" in x[1] else x[1]) for x in Dict] </code></pre> <p>Results in:</p> <pre><code>[('Main Menu-046', ['PASS']), ('Main Menu-047', ['FAIL']),...
1
2016-07-12T20:11:57Z
[ "python", "dictionary" ]
Replace list value in Python dictionary
38,337,955
<p>I have the following dictionary. For objects that have the value <code>['FAIL', 'PASS']</code>, I'd like to replace it with <code>'PASS'</code> only.</p> <pre><code>Dict = [('Main Menu-046', ['PASS']), ('Main Menu-047', ['FAIL']), ('Main Menu-044', ['FAIL', 'PASS']), ('Main Menu-045', ['PASS']), ('Main Menu-042', [...
0
2016-07-12T20:04:16Z
38,338,211
<p>You don't use a dict but a list of pair <code>(Main, [PASS/FAIL])</code></p> <p>If you want a dictionary, you can create it by <code>d = { key:value, key:value ... }</code> or by <code>d = dict()</code> and add item by simply <code>d['newkey'] = value</code></p> <p>Plus, if you wish, you can apply default value li...
0
2016-07-12T20:20:30Z
[ "python", "dictionary" ]
Python Selenium - How to specify a client certificate to use in client SSL authentication
38,337,976
<p>I looked at all the possible keys in all json files based on the answer in <a href="http://stackoverflow.com/questions/38316910/python-selenium-what-are-possible-keys-in-firefox-webdriver-profile-preference">Python Selenium - What are possible keys in FireFox webdriver profile preferences</a>, but I couldn't find a ...
6
2016-07-12T20:05:22Z
38,498,525
<p>As I can see in the <a href="https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/firefox/firefox_profile.py" rel="nofollow">source code</a>, you could create a firefox profile with a parameter (<code>profile_directory</code>) and get firefox launched with the given profile. I think you may also ...
-1
2016-07-21T08:09:18Z
[ "python", "selenium", "authentication", "ssl" ]
Reformatting text in Python
38,338,068
<p>I am new to python and having great difficulty parsing through a log file. Can you please help me understand how I can accomplish the below in the most Pythonic way.</p> <pre><code>----- Log Entry 5 ----- Time : 2016-07-12 09:00:00 Animal : Brown Bear Bird : White Owl Fish : Salmon ----- Lo...
0
2016-07-12T20:11:26Z
38,339,421
<p>There are a lot of ways to do this. Personally I would avoid using regex for this because it probably won't be more efficient and the expression becomes cumbersome and inflexible. Here is something I came up with:</p> <pre><code>class Entry: def __init__(self): self.time = None self.animal = Non...
1
2016-07-12T21:49:31Z
[ "python", "count", "transpose" ]
pandas convert row values to binary format
38,338,070
<p>I am looking for a way to convert column values of my dataframe to boolean values. In my dataframe below, I have columns x,y,z. </p> <p>I prepared a reference dict where I got all the unique values from each column, sorted and separated by colons. Finally, I concatenated my dict with the dataframe: Here is what my ...
0
2016-07-12T20:11:31Z
38,338,878
<p>not sure how scalable this is, but here's one idea:</p> <pre><code>df = pd.DataFrame([["0,1", "10", "10,300"], ["1", "5", "300,0"], ["10,1,0", "", "300,10"]], columns = ["x", "y", "z"]) bin_dict_x = {'0': 100, '1': 10, '10': 1} bin_dict_y = {'5': 10, '10': 1} bin_dict_z = {'0': 100, '10': 10, '300': 1} def to_bin...
1
2016-07-12T21:06:02Z
[ "python", "pandas" ]
How to print first 10 lines instead of the whole list using pprint
38,338,102
<p>What I am trying to accomplish is printing 10 lines only instead of the whole list using <code>pprint(dict(str_types))</code></p> <p>Here is my code</p> <pre><code>from collections import defaultdict str_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) expected = ["Street", "Avenue", "Boulevard", "Drive", "Cour...
-3
2016-07-12T20:13:26Z
38,338,290
<p>Use <a href="https://docs.python.org/2/library/pprint.html#pprint.pformat" rel="nofollow"><code>pprint.pformat</code></a> to get back the string representation of the object instead of printing it directly, then you can split it up by lines and only print out the first few:</p> <pre><code>whole_repr = pprint.pforma...
0
2016-07-12T20:26:01Z
[ "python" ]
A fast method for comparing a value in one Panda’s row to another in a previous row?
38,338,127
<p>I have a DataFrame, df, that looks like:</p> <pre><code>ID | TERM | DISC_1 1 | 2003-10 | ECON 1 | 2002-01 | ECON 1 | 2002-10 | ECON 2 | 2003-10 | CHEM 2 | 2004-01 | CHEM 2 | 2004-10 | ENG...
2
2016-07-12T20:15:24Z
38,338,611
<p>Here's a start:</p> <pre><code>df = df.sort_values(['ID', 'TERM']) gb = df.groupby('ID').DISC_1 df['Change'] = df.TERM[gb.apply(lambda x: x != x.shift().bfill())] df.Change = df.Change.fillna(0) </code></pre>
5
2016-07-12T20:47:41Z
[ "python", "pandas", "group-by" ]
A fast method for comparing a value in one Panda’s row to another in a previous row?
38,338,127
<p>I have a DataFrame, df, that looks like:</p> <pre><code>ID | TERM | DISC_1 1 | 2003-10 | ECON 1 | 2002-01 | ECON 1 | 2002-10 | ECON 2 | 2003-10 | CHEM 2 | 2004-01 | CHEM 2 | 2004-10 | ENG...
2
2016-07-12T20:15:24Z
38,338,797
<p>I've never been a big pandas user, so my solution would involve spitting that df out as a csv, and iterating over each row, while retaining the previous row. If it is properly sorted (first by ID, then by Term date) I might write something like this... </p> <pre><code>import csv with open('inputDF.csv', 'rb') as i...
2
2016-07-12T21:00:01Z
[ "python", "pandas", "group-by" ]
Get the name of the classes I defined in django model
38,338,135
<p>I am trying to get the names of the classes I defined in my models.py file. The closest I could get is to recover all the models in the application: </p> <pre><code>modelsList = django.apps.apps.get_models (include_auto_created=False)` </code></pre> <p>which gives:</p> <pre><code>&lt;class 'django.contrib.admin...
0
2016-07-12T20:16:02Z
38,338,788
<p>Based on <a href="http://stackoverflow.com/questions/29738976/how-can-i-get-all-models-in-django-1-8">a answer from here</a>:</p> <pre><code>from django.apps import apps def get_models(app_name): myapp = apps.get_app_config(app_name) return myapp.models.values() </code></pre>
0
2016-07-12T20:59:32Z
[ "python", "django", "django-models" ]
Get the name of the classes I defined in django model
38,338,135
<p>I am trying to get the names of the classes I defined in my models.py file. The closest I could get is to recover all the models in the application: </p> <pre><code>modelsList = django.apps.apps.get_models (include_auto_created=False)` </code></pre> <p>which gives:</p> <pre><code>&lt;class 'django.contrib.admin...
0
2016-07-12T20:16:02Z
38,338,963
<p>You can get the model name for a model <code>Model</code> with <code>Model._meta.object_name</code>. So you could do something like:</p> <pre><code>import django.apps models = django.apps.apps.get_models(include_auto_created=False) model_names = [m._meta.object_name for m in models] </code></pre>
0
2016-07-12T21:12:15Z
[ "python", "django", "django-models" ]
How to remove grey boundary lines in a map when plotting a netcdf using imshow in matplotlib?
38,338,177
<p>Is it possible to remove the grey boundary lines around the in following map? I am trying to plotting a netcdf using <code>matplotlib</code>.</p> <pre><code>from netCDF4 import Dataset # clarify use of Dataset import matplotlib.pylab as plt fnc = Dataset(ncfile, 'r') lat = fnc.variables['latitude'][:] lon = fnc.var...
0
2016-07-12T20:17:52Z
38,340,441
<p>Those gray boundaries are an interpolation artifact from <code>imshow</code>. To get rid of them, do:</p> <pre><code>imgplot = plt.imshow(mydata, cmap = 'YlGn', interpolation='none') </code></pre> <p>Or plot through <code>Basemap</code> and control drawing explicitly, as in <a href="http://joehamman.com/2013/10/12...
2
2016-07-12T23:35:54Z
[ "python", "matplotlib", "imshow" ]
Homebrew Python SQLite not building on macOS Sierra
38,338,206
<p>I've installed Homebrew Python on my computer running macOS sierra. The problem is that SQLite doesn't work, at all:</p> <pre><code>Python 2.7.11 (default, Jul 8 2016, 15:45:55) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.24.1)] on darwin Type "help", "copyright", "credits" or "license" for more informatio...
0
2016-07-12T20:20:19Z
39,129,788
<p>Using the formula from <a href="https://github.com/Homebrew/homebrew-core/pull/3134" rel="nofollow">this pull request</a> solved my problem. Thanks to @user2960428 for the link. The PR hasn't been merged yet, so you can install it like this:</p> <pre class="lang-none prettyprint-override"><code>$ brew install https...
1
2016-08-24T17:40:42Z
[ "python", "sqlite", "homebrew", "macos-sierra" ]
Defining colors of Matplotlib 3D bar plot
38,338,221
<p>I can't figure out the right way to set a cmap (or colors) for a 3d bar plot in matplotlib in my iPython notebook. I can setup my chart correctly (28 x 7 labels) in the X and Y plane, with some random Z values. The graph is hard to interpret, and one reason is that the default colors for the x_data labels [1,2,3,4,5...
0
2016-07-12T20:21:03Z
38,339,967
<pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(18,12)) ax = fig.add_subplot(111, projection='3d') x_data, y_data = np.meshgrid(np.arange(5),np.arange(3)) z_data = np.random.rand(3,5) colors = ['r','g','b'] # colors for every line of y #...
1
2016-07-12T22:38:49Z
[ "python", "matplotlib", "3d", "ipython-notebook" ]
Obtaining integer from String when converting from python 2 to python 3
38,338,335
<p>I have a program in python2, however, I am rewriting it in python3. I read in a netcdf file, and save the variables. One of the variables should be a string, and I need to turn that string into an integer. In python 2 I use this method:</p> <pre><code>nums = fid.variables['num'][:] &gt;&gt;&gt; nums[0] &gt;&gt;&...
1
2016-07-12T20:28:51Z
38,339,246
<p>Given your edit, your problem is that nums is a container of containers, so your list comprehension isn't working, might I suggest a nested comprehension?:</p> <pre><code>&gt;&gt;&gt; nums = [[b'0',b'1',b'2',b'3'], [b'0',b'1',b'2',b'3']] &gt;&gt;&gt; [[b.decode('utf8') for b in t] for t in nums] [['0', '1', '2', '3...
1
2016-07-12T21:33:06Z
[ "python", "string", "numpy", "integer", "byte" ]
How Do I Send an HTTP Data Request With Python?
38,338,339
<p>I am a beginner so I apologize if my question is very obvious or not worded correctly.</p> <p>I need to send a request to a URL so data can then be sent back in XLM format. The URL will have a user specific login and password, so I need to incorporate that as well. Also there is a port (port 80) that I need to in...
-1
2016-07-12T20:29:11Z
38,343,411
<p>Here is a python documentation on how to fetch internet resources using the urllib package. </p> <p>It talks about getting the data, storing it in a file, sending data and some basic authentication. </p> <p><a href="https://docs.python.org/3/howto/urllib2.html" rel="nofollow">https://docs.python.org/3/howto/urllib...
0
2016-07-13T05:37:39Z
[ "python", "xml", "http", "request" ]
Efficient way to select all pairs of vertices that share common neighbors in a bipartite network
38,338,351
<p>I need select all pairs of vertices of the same type that share common neighbors in a bipartite network</p> <p>For instance:</p> <p><a href="http://i.stack.imgur.com/KvDwF.png" rel="nofollow"><img src="http://i.stack.imgur.com/KvDwF.png" alt="enter image description here"></a></p> <p>In this graph I have: (A,B), ...
0
2016-07-12T20:29:57Z
38,346,463
<p>You are basically calculating the edge lists of the two bipartite projections of your original network. igraph has a built-in method for this, assuming that your vertices have a vertex attribute named <code>type</code> that describes which part of the graph the vertices belong to:</p> <pre><code>&gt;&gt;&gt; g=Grap...
1
2016-07-13T08:31:21Z
[ "python", "graph", "complexity-theory", "igraph", "bipartite" ]
how to add incremental numbers in pyspark map
38,338,372
<p>I have this code:</p> <pre><code>import time from datetime import datetime ts = time.time() dt = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') claims_data = data.map(lambda x: x.split(",")) claim_id = claims_data.map(lambda x: ( x[9], 'Claim_id', '0', 'Claim_id', 'Claim', 1, )) ...
0
2016-07-12T20:31:09Z
38,359,156
<p>By your example I'm assuming you want your indices to be 1-based (not-0).</p> <p>If so this should get you what you want (can use this template for both variables):</p> <pre><code>claim_ids = map(lambda x: ( x[1][13], 'BeginDOS', '0', 'BeginDOS', 'Claim', x[0]+1, ),enumerate(claims_data)) ...
0
2016-07-13T18:23:36Z
[ "python", "apache-spark", "lambda", "pyspark", "rdd" ]
Pudb source screen is squished, other screens are expanded (see screenshot)
38,338,375
<p>Any solution to this? This happens in certain folders, not in every folder. Cannot figure out what causes this.</p> <p>Worth mentioning that another c++ program is invoking the python script that has 'from pudb import set_trace' and 'set_trace()' in it.</p> <p><a href="http://i.stack.imgur.com/zEekT.png" rel="nofo...
0
2016-07-12T20:31:50Z
38,340,461
<p>Fixed but not root-caused. Turns out, a redirection (of the logs into a file) in the run-script was causing it. Removing the redirection fixed it. </p> <p><a href="http://i.stack.imgur.com/zoXfD.png" rel="nofollow"><img src="http://i.stack.imgur.com/zoXfD.png" alt="enter image description here"></a></p>
0
2016-07-12T23:38:14Z
[ "python", "pudb" ]
Sort and limit number of bars to display on bargraph
38,338,396
<p>I have a dataset of traffic violations and want to display only the top 10 violations per month on a bargraph. Can I limit the number of bars after sorting values to display only the top 10? There are 42 different column names of traffic violations.</p> <pre><code>month_jan = df[df.MonthName == "Jan"] month_jan[fe...
1
2016-07-12T20:33:08Z
38,339,384
<p><code>Series</code> objects have a <code>.head</code> method, just like <code>DataFrame</code>s (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.head.html" rel="nofollow">docs</a>). This allows you to select the top N items very elegantly with <code>data.head(N)</code>. Here's a complete...
0
2016-07-12T21:46:30Z
[ "python", "pandas", "bar-chart" ]
Sort and limit number of bars to display on bargraph
38,338,396
<p>I have a dataset of traffic violations and want to display only the top 10 violations per month on a bargraph. Can I limit the number of bars after sorting values to display only the top 10? There are 42 different column names of traffic violations.</p> <pre><code>month_jan = df[df.MonthName == "Jan"] month_jan[fe...
1
2016-07-12T20:33:08Z
38,381,589
<p>This will work:</p> <pre><code>month_jan[feature_cols].sum().sort_values(ascending=0)[:10].plot(kind='bar') </code></pre>
0
2016-07-14T18:27:00Z
[ "python", "pandas", "bar-chart" ]
Rendering django form in view
38,338,483
<p>I am new to django, and I want to extend the user model with another class. However, I am not sure how to get the form to work properly with the class Device. I would like temperature, and battery to show up in the form. Thank you very much in advance :)</p> <p>models.py</p> <pre><code>class Device(models.Model): ...
0
2016-07-12T20:38:04Z
38,338,844
<p>Remove the <code>device</code> field from the <code>UserProfile</code> form - you want to edit the existing device, not change it to a different device.</p> <pre><code>class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('deviceNb',) </code></pre> <p>Then create a d...
1
2016-07-12T21:04:07Z
[ "python", "django", "forms" ]
applying filters to Google Analytics API in python
38,338,579
<p>I am brand new to writing queries to Google analytics and am interested in adding a filter to the method below. Specifically, to filter out locations, but I keep getting an error anytime there is something other than 'EXACT' in the operator field. for the dimensionFilterClauses.</p> <p>is there a list of valid oper...
0
2016-07-12T20:45:01Z
38,339,198
<p>It seems, according to here: <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#dimensionfilterclause" rel="nofollow">https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#dimensionfilterclause</a></p> <p>...which leads to her...
0
2016-07-12T21:29:34Z
[ "python", "google-analytics-v4" ]
Trouble connecting to phantomJs webdriver using python and selenium
38,338,609
<p>I am trying to run a python script on a linux server which uses selenium and a phantomjs webdriver; however, I keep getting the following error message:</p> <pre><code>selenium.common.exceptions.WebDriverException: Message: Service /home/ubuntu/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs unexpectedly ...
1
2016-07-12T20:47:22Z
38,338,846
<pre><code>sudo apt-get install libfontconfig </code></pre> <p>This solved my issue.</p>
2
2016-07-12T21:04:16Z
[ "python", "linux", "selenium", "phantomjs" ]
__dict__ Doesn't Allow Call to Method in Python
38,338,688
<p>I am creating a dictionary of objects that I'd like to save and re-load at a different time (I want to do this with the "json" module, not "pickle").</p> <p>I have one class created (let's call it "Ball"), and the dictionary just contains many different instances of that class. The way it looks is:</p> <pre><code...
0
2016-07-12T20:52:54Z
38,338,740
<p>Ultimately, <code>json</code> doesn't support serializing arbitrary python objects. If you want to do that, you can have a look at <code>pickle</code>.</p> <p>Alternatively, you can create an alternate constructor on your <code>Ball</code> that will initialize it with values from the <code>dict</code>:</p> <pre><...
1
2016-07-12T20:56:25Z
[ "python", "json", "dictionary", "methods", "save" ]
Why do we import scikit-learn with sklearn?
38,338,822
<p>Why is that we install the scikit-learn package with: </p> <pre><code>conda install scikit-learn </code></pre> <p>but then import (modules from) the package in a script using the name <code>sklearn</code>, e.g.:</p> <pre><code>from sklearn import x </code></pre>
1
2016-07-12T21:02:23Z
38,338,855
<p><code>scikit-learn</code> isn't a valid identifier in python, so it can't be <em>that</em>. I suppose that they could have named the package <code>scikit_learn</code>, but that's a lot to type so I suppose they just decided to shorten the package name for convenience.</p> <p>Of course, if you're so inclined, you <...
2
2016-07-12T21:04:39Z
[ "python", "scikit-learn" ]
Python: stdout to both console and textfile including errors
38,338,823
<p>I would like to print the output of python to both console and a textfile including errors, if any.</p> <p>So far my attempts are these:</p> <p><strong>Using console:</strong></p> <pre><code># mystdout.py # note that it has missing ) sign print("hello # in the terminal: chmod a+x mystdout.py; ./mystdout.py 2&gt...
1
2016-07-12T21:02:29Z
38,338,901
<p>If you are using bash (minimum version 4), you can run: <code>./mystdout |&amp; tee output.txt</code>. Otherwise your suggestion <code>./mystdout 2&gt;&amp;1 | tee output.txt</code> should also work.</p>
3
2016-07-12T21:07:36Z
[ "python", "file-io" ]
Python: stdout to both console and textfile including errors
38,338,823
<p>I would like to print the output of python to both console and a textfile including errors, if any.</p> <p>So far my attempts are these:</p> <p><strong>Using console:</strong></p> <pre><code># mystdout.py # note that it has missing ) sign print("hello # in the terminal: chmod a+x mystdout.py; ./mystdout.py 2&gt...
1
2016-07-12T21:02:29Z
38,338,932
<p>Solution from @Pierre should work. Otherwise I would suggest intercept stdout/stderr from external process and use logging with two handlers: one for console, another for specific file. Here is and <a href="http://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout">example</...
2
2016-07-12T21:09:43Z
[ "python", "file-io" ]
Python: stdout to both console and textfile including errors
38,338,823
<p>I would like to print the output of python to both console and a textfile including errors, if any.</p> <p>So far my attempts are these:</p> <p><strong>Using console:</strong></p> <pre><code># mystdout.py # note that it has missing ) sign print("hello # in the terminal: chmod a+x mystdout.py; ./mystdout.py 2&gt...
1
2016-07-12T21:02:29Z
38,381,010
<p>I am using bash 3.2.53. Unfortunately the solution by Pierre does not worked for me. And solution referred by grundic was too complicated for me. </p> <p>So, I came up with the easy solution:<br> When the python run without errors, This method worked for me:</p> <pre><code>python3 a.py | tee aout.txt # to test o...
0
2016-07-14T17:53:38Z
[ "python", "file-io" ]
Benford's law test function inside groupby.agg
38,338,864
<p>Below is a small sample of my dataframe which is 25000 odd rows long:</p> <pre><code> In [58]: df Out[58]: Send_Agent Send_Amount 0 ADR000264 361.940000 1 ADR000264 12.930000 2 ADR000264 11.630000 3 ADR000264 12.930000 4 ADR000264 64.630000 5 ADR000264 12.930000 6 ...
3
2016-07-12T21:05:27Z
38,339,085
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>, because <code>agg</co...
1
2016-07-12T21:20:54Z
[ "python", "pandas" ]
Benford's law test function inside groupby.agg
38,338,864
<p>Below is a small sample of my dataframe which is 25000 odd rows long:</p> <pre><code> In [58]: df Out[58]: Send_Agent Send_Amount 0 ADR000264 361.940000 1 ADR000264 12.930000 2 ADR000264 11.630000 3 ADR000264 12.930000 4 ADR000264 64.630000 5 ADR000264 12.930000 6 ...
3
2016-07-12T21:05:27Z
38,339,935
<p>Cool project. I will use a randomly generated dataset for illustration:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(0) Send_Amount = 10**(np.random.randint(1, 9, 10**6)) * \ (np.random.choice(np.arange(1, 10), p=np.log10(1+(1/np.arange(...
1
2016-07-12T22:35:24Z
[ "python", "pandas" ]
Django - authenticate() return None
38,338,868
<p>I read many of topic about this problem and the problem is always there. When I submit my login form, the authenticate function() returns None. I used the function set_password() for the registration and it changes nothing. </p> <p>Here is my code (also <a href="https://repl.it/CbTW/0" rel="nofollow">here</a>):</p>...
0
2016-07-12T21:05:36Z
38,339,125
<p>Your problem is that you try to authenticate user against the email / password pair and there is no backend that accepts such a pair. The model backend accepts username / password pair, so to authenticate with email use:</p> <pre><code>(...) if form.is_valid(): email = form.cleaned_data["email"] password = ...
1
2016-07-12T21:23:53Z
[ "python", "django", "authentication", "nonetype" ]
How to extract data from pyplot figure
38,338,900
<p><a href="http://stackoverflow.com/questions/8938449/how-to-extract-data-from-matplotlib-plot">I already checked out this question, but it didn't solve my problem.</a></p> <p>Hello! I have a pyplot figure:</p> <p>def foo(data): fig, ax = plt. subplots(figsize=(20, 10), dpi=100)</p> <pre><code> xaxis = (...
0
2016-07-12T21:07:34Z
38,376,216
<p>I think the following code does what you want for a simple line plot:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def foo(xaxis, yaxis): fig, ax = plt. subplots(figsize=(20, 10), dpi=100) curve = ax.plot(xaxis, yaxis) # curve = [Line2D object] return curve[0].get_xdata(), cur...
1
2016-07-14T13:56:45Z
[ "python", "matplotlib" ]
Retrieving multiple mongo documents from cursor.next() for better performance
38,338,911
<p>I have the following code to gather arrays (stored as pickled documents in a Mongo collection) and stack them into a 2D numpy matrix:</p> <pre><code>db = MongoClient()['db'] total = db.command('collStats', 'collection')['count'] collection = db['collection'] X, Y = np.array([]), np.array([]) pipe = [{'$sample': {'...
1
2016-07-12T21:08:10Z
38,339,378
<p>There is a <code>cursor.toArray()</code> that returns everything at once. </p>
-1
2016-07-12T21:46:00Z
[ "python", "mongodb", "python-2.7", "numpy" ]
Retrieving multiple mongo documents from cursor.next() for better performance
38,338,911
<p>I have the following code to gather arrays (stored as pickled documents in a Mongo collection) and stack them into a 2D numpy matrix:</p> <pre><code>db = MongoClient()['db'] total = db.command('collStats', 'collection')['count'] collection = db['collection'] X, Y = np.array([]), np.array([]) pipe = [{'$sample': {'...
1
2016-07-12T21:08:10Z
38,469,786
<p>Best way I found to improve performance:</p> <ol> <li>Convert each item to a list</li> <li>Append that list to a list of lists </li> <li>Convert to a 2D numpy array</li> </ol> <p>So, for my case, like this:</p> <pre><code>xy = pickle.loads(curosor.next()['array']).tolist() X, Y = [xy[0:-1]], [[xy[-1]]] for i in...
0
2016-07-19T22:53:55Z
[ "python", "mongodb", "python-2.7", "numpy" ]
Function only prints the correct statement for the last item in the list?
38,338,969
<p>So the question asks:</p> <blockquote> <p>Write a function <code>is_member()</code> that takes a value (i.e. a number, string, etc) <code>x</code> and a list of values <code>a</code>, and returns <code>True</code> if <code>x</code> is a member of <code>a</code>, <code>False</code> otherwise. (Note that this is ex...
0
2016-07-12T21:12:30Z
38,338,990
<pre><code>def is_member(value, list1): for e in list1: if e == value: ans = 'Yes, the value ' + str(value) + ' is in the list' break else: ans = 'No, the value ' + str(value) + ' is not in the list' return ans print is_member(2, [1, 2, 3, 4, 5, 6, 7]) </cod...
3
2016-07-12T21:14:28Z
[ "python", "list", "iteration" ]