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
Getting unbound method error?
39,762,188
<p>I tried to run this code below </p> <pre><code>class TestStaticMethod: def foo(): print 'calling static method foo()' foo = staticmethod(foo) class TestClassMethod: def foo(cls): print 'calling class method foo()' print 'foo() is part of class: ', cls.__name__...
0
2016-09-29T05:37:56Z
39,763,418
<p>You should not indent </p> <blockquote> <p>foo = staticmethod(function_name)</p> </blockquote> <p>in function(foo) itself,</p> <p>Instead give this a try:</p> <pre><code>class TestStaticMethod: def foo(): print 'calling static method foo()' foo = staticmethod(foo) </code></pre> <p>or </p...
0
2016-09-29T06:55:42Z
[ "python" ]
How insert into a new table from another table cross joined with another table
39,762,285
<p>I'm using Python and SQLite to manipulate a database. </p> <p>I have a SQLite table <code>Movies</code> in database <code>Data</code> that looks like this:</p> <pre><code>| ID | Country +----------------+------------- | 1 | USA, Germany, Mexico | 2 | Brazil, Peru | 3 ...
0
2016-09-29T05:44:50Z
39,763,337
<p>Here's a workaround which successfully got the result you wanted.</p> <hr> <p>Instead of having to write <code>con = sqlite3.connect("data.db")</code> and then having to write <code>con.commit()</code> and <code>con.close()</code>, you can shorten your code to written like this:</p> <pre><code>with sqlite3.connec...
0
2016-09-29T06:51:25Z
[ "python", "sqlite" ]
How insert into a new table from another table cross joined with another table
39,762,285
<p>I'm using Python and SQLite to manipulate a database. </p> <p>I have a SQLite table <code>Movies</code> in database <code>Data</code> that looks like this:</p> <pre><code>| ID | Country +----------------+------------- | 1 | USA, Germany, Mexico | 2 | Brazil, Peru | 3 ...
0
2016-09-29T05:44:50Z
39,765,291
<p>The current error is probably caused by a typo or other minor problem. I could create the databases described here and successfully do the insert after fixing minor errors: a missing backslash at an end of line and adding qualifiers for the selected columns.</p> <p>But I also advise your to use aliases for the tabl...
0
2016-09-29T08:33:41Z
[ "python", "sqlite" ]
Working of Cache-mem using Queue in Python
39,762,452
<p>I write a code to simulate the working of cache-memory. In this model, i try to realize the FIFO-algorhythm which allow to delete the last unused element (data, value, whatever). I wrote a special function, which give me a list <strong>o</strong> with numbers (these numbers are addresses in memory).</p> <pre><code...
0
2016-09-29T05:57:08Z
39,762,937
<p>You cant do that with Queues I think, instead use collections.dequeue which are almost similar while collections have fast append(), pop(). You can change your code first line to <code>q=collections.deque([],800)</code> and in place of q.put,q.get use <code>q.append</code> ,<code>q.popleft()</code>.</p>
0
2016-09-29T06:29:37Z
[ "python", "list", "caching", "queue" ]
How to run django server with ACTIVATED virtualenv using batch file (.bat)
39,762,490
<p>I found this post to be useful on <a href="http://stackoverflow.com/questions/3027160/how-to-code-a-batch-file-to-automate-django-web-server-start">how to code a batch file to automate django web server start</a>.</p> <p>But the problem is, there is <strong>no virtualenv</strong> activated, How can i activate it be...
0
2016-09-29T06:00:01Z
39,762,750
<p>try <code>\path\to\env\Scripts\activate</code></p> <p>and look at <a href="https://virtualenv.pypa.io/en/stable/userguide/#activate-script" rel="nofollow">virtualenv docs</a></p>
1
2016-09-29T06:17:50Z
[ "python", "django", "windows", "batch-file" ]
How to run django server with ACTIVATED virtualenv using batch file (.bat)
39,762,490
<p>I found this post to be useful on <a href="http://stackoverflow.com/questions/3027160/how-to-code-a-batch-file-to-automate-django-web-server-start">how to code a batch file to automate django web server start</a>.</p> <p>But the problem is, there is <strong>no virtualenv</strong> activated, How can i activate it be...
0
2016-09-29T06:00:01Z
39,764,400
<p>Call the <code>activate.bat</code> script in your batch file, before you run <code>manage.py</code>,</p> <pre><code>CALL \path\to\env\Scripts\activate.bat python manage.py runserver </code></pre>
1
2016-09-29T07:50:14Z
[ "python", "django", "windows", "batch-file" ]
How to run django server with ACTIVATED virtualenv using batch file (.bat)
39,762,490
<p>I found this post to be useful on <a href="http://stackoverflow.com/questions/3027160/how-to-code-a-batch-file-to-automate-django-web-server-start">how to code a batch file to automate django web server start</a>.</p> <p>But the problem is, there is <strong>no virtualenv</strong> activated, How can i activate it be...
0
2016-09-29T06:00:01Z
39,908,152
<p>Found my solution by encoding this:</p> <pre><code>@echo off cmd /k "cd /d C:\Users\[user]\path\to\your\env\scripts &amp; activate &amp; cd /d C:\Users\[user]\path\to\your\env\[projectname] &amp; python manage.py runserver" </code></pre>
0
2016-10-07T01:49:54Z
[ "python", "django", "windows", "batch-file" ]
Numerically order a list based on a pattern
39,762,521
<p>I have a list of file names in the form:</p> <pre><code>['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] </code></pre> <p>I wonder how to sort this list numerically to obtain the output:</p> <pre><code>['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt...
2
2016-09-29T06:02:56Z
39,762,687
<p>You should split needed numbers and convert them to <code>int</code></p> <pre><code>ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] def numeric(i): return tuple(map(int, i.replace('.txt', '').split('_')[1:])) sorted(ss, key=numeric) # ['comm_1_1.txt', 'c...
3
2016-09-29T06:14:15Z
[ "python", "sorting" ]
Numerically order a list based on a pattern
39,762,521
<p>I have a list of file names in the form:</p> <pre><code>['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] </code></pre> <p>I wonder how to sort this list numerically to obtain the output:</p> <pre><code>['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt...
2
2016-09-29T06:02:56Z
39,762,770
<p>I don't really think its a best answer, but you can try it out. </p> <pre><code>l = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] d = {} for i in l: filen = i.split('.') key = filen[0].split('_') d[int(key[2])] = i for key in sorted(d): ...
1
2016-09-29T06:19:27Z
[ "python", "sorting" ]
Numerically order a list based on a pattern
39,762,521
<p>I have a list of file names in the form:</p> <pre><code>['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] </code></pre> <p>I wonder how to sort this list numerically to obtain the output:</p> <pre><code>['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt...
2
2016-09-29T06:02:56Z
39,762,781
<p>One technique used for this kind of "human sorting" is to split keys to tuples and convert numeric parts to actual numbers:</p> <pre><code>ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] print(sorted(ss, key=lambda x : map((lambda v: int(v) if "0" &lt;= v[0] ...
2
2016-09-29T06:20:17Z
[ "python", "sorting" ]
NameError: name 'addition' is not defined
39,762,550
<p>I am getting <code>NameError: name 'addition' is not defined</code> while running following code</p> <pre><code>class Arithmetic: def __init__(self, a, b): self.a = a self.b = b def addition(self): c = a + b print"%d" %c def subtraction(self): c=a-b prin...
-3
2016-09-29T06:04:49Z
39,762,630
<p>You first have to create object of class and then you can access class function. Try this:</p> <pre><code>a = Arithmatic() a.addition(5,4) </code></pre>
0
2016-09-29T06:10:24Z
[ "python" ]
NameError: name 'addition' is not defined
39,762,550
<p>I am getting <code>NameError: name 'addition' is not defined</code> while running following code</p> <pre><code>class Arithmetic: def __init__(self, a, b): self.a = a self.b = b def addition(self): c = a + b print"%d" %c def subtraction(self): c=a-b prin...
-3
2016-09-29T06:04:49Z
39,762,813
<p>Check out this piece of code:</p> <pre><code>class Arithmetic(): def init(self, a, b): self.a = a self.b = b def addition(self): c = self.a + self.b print"addition %d" %c def subtraction(self): c = self.a - self.b print"substraction %d" %c obj = Arithme...
0
2016-09-29T06:21:57Z
[ "python" ]
NameError: name 'addition' is not defined
39,762,550
<p>I am getting <code>NameError: name 'addition' is not defined</code> while running following code</p> <pre><code>class Arithmetic: def __init__(self, a, b): self.a = a self.b = b def addition(self): c = a + b print"%d" %c def subtraction(self): c=a-b prin...
-3
2016-09-29T06:04:49Z
39,763,813
<p>If you want to use your 'addition' method, you first need to instantiate an Arithmetic() object and use dot notation to call their functions. Make sure you properly indent your code because not only is it breaking a lot of PEP 8 rules but it just looks plain messy. In your first definition, don't forget you have to ...
1
2016-09-29T07:17:29Z
[ "python" ]
Export BeautifulSoup scraping results to CSV; scrape + include image values in column
39,762,565
<p>For this project, I am scraping data from a database and attempting to export this data to a spreadsheet for further analysis.</p> <p>While my code seems mostly to work well, when it comes to the last bit--exporting to CSV--I am having no luck. This question has been asked a few times, however it seems the answers ...
0
2016-09-29T06:05:48Z
39,763,317
<p>The following should correctly export your data to a CSV file:</p> <pre><code>from bs4 import BeautifulSoup import requests import re import csv url = "http://www.elections.ca/WPAPPS/WPR/EN/NC?province=-1&amp;distyear=2013&amp;district=-1&amp;party=-1&amp;pageno={}&amp;totalpages=55&amp;totalcount=1368&amp;second...
1
2016-09-29T06:50:17Z
[ "python", "html", "python-3.x", "csv", "beautifulsoup" ]
Dataframe returning None value
39,762,576
<p>I was returning a dataframe of characters from GOT such that they were alive and predicted to die, but only if they have some house name. (important person). I was expecting it to skip NaN's, but it returned them as well. I've attached screenshot of output. Please help.</p> <p>PS I haven't attached any spoilers so ...
3
2016-09-29T06:06:25Z
39,762,595
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns:</p> <pre><code>b = df.ix...
2
2016-09-29T06:07:49Z
[ "python", "pandas", "indexing", "multiple-columns", null ]
Python Issue after Windows 10 Update
39,762,666
<p>I'm going to make this question as succinct and to the point as possible. I have a jupyter notebook that worked perfectly yesterday. Today, my windows 10 machine demanded an update and after updating, the jupyter notebook now cannot run. I can import libraries and define functions, but when I actually go about using...
0
2016-09-29T06:12:38Z
39,763,786
<p>Maybe the windows update meant well, but it created a lot of upheaval on my system. I had to reconfigure a lot of settings ranging from privacy to monitor display resolution. I believe some registry entries are different, although I typically don't look registry entries on a day to day basis. Some registry switcharo...
0
2016-09-29T07:16:03Z
[ "python", "windows", "jupyter-notebook" ]
Parse dictionary looking for a specific string
39,762,673
<p>I'm writing a python script to make an API call to our Cisco ASA firewall and the information returned from the firewall is placed into a dictionary. I then need to parse through this dictionary looking for a specific string. The problem is, there's 1 key and what looks to be one large value. I've inserted an exampl...
0
2016-09-29T06:13:11Z
39,762,762
<p>If you only want to know whether or not a specific IP is in the response string, you can use the <code>in</code> operator:</p> <pre><code>if '2.2.2.2' in resp_dict['response'][0]: print('Found') </code></pre> <p>Or generalized:</p> <pre><code>ip = '2.2.2.2' if ip in resp_dict['response'][0]: print('{} fou...
2
2016-09-29T06:18:57Z
[ "python", "dictionary", "networking" ]
Parse dictionary looking for a specific string
39,762,673
<p>I'm writing a python script to make an API call to our Cisco ASA firewall and the information returned from the firewall is placed into a dictionary. I then need to parse through this dictionary looking for a specific string. The problem is, there's 1 key and what looks to be one large value. I've inserted an exampl...
0
2016-09-29T06:13:11Z
39,762,858
<p>Extract all IP and then you can search for a particular IP address in the list or loop through all of them. Alternately you can search directly in the string as @DeepSpace says</p> <pre><code>import re d = {u'response': [u'object-group network ng-enc-incoming-ftp-outside\n network-object 1.1.1.1 255.255.255.128\n ...
0
2016-09-29T06:25:10Z
[ "python", "dictionary", "networking" ]
Copy file from URI format path to local path
39,763,063
<p>I am trying to copy a file which is on a server and all I've got is it's URI format path.<br> I've been trying to implement copying in C# .NET 4.5, but seems like CopyFile is not good with handling URI formats.<br> So I've used IronPython with shutil, but seems like it is also not good with URI format paths. </p> ...
0
2016-09-29T06:36:51Z
39,763,131
<p>you can use a webclient and then get the file on a particular folder.</p> <pre><code>using (WebClient wc = new WebClient()) wc.DownloadFile("http://sitec.com/web/myfile.jpg", @"c:\images\xyz.jpg"); </code></pre> <p>or you can also use: <code>HttpWebRequest</code> inc ase you just want to read the content from ...
1
2016-09-29T06:40:35Z
[ "c#", "python", ".net", "ironpython" ]
Copy file from URI format path to local path
39,763,063
<p>I am trying to copy a file which is on a server and all I've got is it's URI format path.<br> I've been trying to implement copying in C# .NET 4.5, but seems like CopyFile is not good with handling URI formats.<br> So I've used IronPython with shutil, but seems like it is also not good with URI format paths. </p> ...
0
2016-09-29T06:36:51Z
39,763,140
<p>With Python</p> <pre><code>import urllib urllib.urlretrieve("http://www.myserver.com/myfile", "myfile.txt") </code></pre> <p><a href="https://docs.python.org/2/library/urllib.html#urllib.urlretrieve" rel="nofollow"><code>urlretrieve</code></a></p> <blockquote> <p>Copy a network object denoted by a URL to a loca...
1
2016-09-29T06:41:02Z
[ "c#", "python", ".net", "ironpython" ]
How to extract subjects in a sentence and their respective dependent phrases?
39,763,091
<p>I am trying to work on subject extraction in a sentence, so that I can get the sentiments in accordance with the subject. I am using <code>nltk</code> in python2.7 for this purpose. Take the following sentence as an example:</p> <p><code>Donald Trump is the worst president of USA, but Hillary is better than him</co...
4
2016-09-29T06:38:17Z
39,764,285
<p>I was recently just solving very similar problem - I needed to extract subject(s), action, object(s). And I open sourced my work so you can check this library: <a href="https://github.com/krzysiekfonal/textpipeliner" rel="nofollow">https://github.com/krzysiekfonal/textpipeliner</a></p> <p>This based on spacy(oppone...
3
2016-09-29T07:42:41Z
[ "python", "nlp", "nltk", "spacy" ]
How to extract subjects in a sentence and their respective dependent phrases?
39,763,091
<p>I am trying to work on subject extraction in a sentence, so that I can get the sentiments in accordance with the subject. I am using <code>nltk</code> in python2.7 for this purpose. Take the following sentence as an example:</p> <p><code>Donald Trump is the worst president of USA, but Hillary is better than him</co...
4
2016-09-29T06:38:17Z
40,014,532
<p>I was going through spacy library more, and I finally figured out the solution through dependency management. Thanks to <a href="https://github.com/NSchrading/intro-spacy-nlp/blob/master/subject_object_extraction.py" rel="nofollow">this</a> repo, I figured out how to include adjectives as well in my subjective verb ...
0
2016-10-13T07:12:48Z
[ "python", "nlp", "nltk", "spacy" ]
How to find the base case for a recursive function that changes a string of characters in a certain way
39,763,109
<p>Lately I have been working with recursion as, according to my professor, it represents pure functional programming approach as neither changes on variables nor side effects take place. Through my previous two questions <a href="http://stackoverflow.com/questions/39704084/how-to-write-a-recursive-function-that-takes...
1
2016-09-29T06:39:05Z
39,763,357
<p>Well, you're iterating over a list of characters, so your base case can be an empty string. Here's a quick example of a recursive function that removes vowels from a string:</p> <pre><code>def strip_vowels(str): if not str: return '' if str[0] in ['a', 'e', 'i', 'o', 'u']: return strip_vowel...
3
2016-09-29T06:52:31Z
[ "python", "recursion", "functional-programming", "discrete-mathematics" ]
How to add additional fields on the base of inputs in django rest framework mongoengine
39,763,119
<p>I am developing an <code>API</code>, using <code>django-rest-framework-mongoengine</code> with <code>MongoDb</code>, I want to append additional fields to the request from the <code>serializer</code> on the base of user inputs, for example If user enters <code>keyword</code>=<code>@rohit49khatri</code>, I want to ap...
0
2016-09-29T06:39:31Z
39,763,861
<p>for the additional question: how to get <code>type</code> parameter?</p> <pre><code># access it via `django rest framework request` self.request.data.get('type', None) # or via `django request` self.request.request.POST.get('type', None) </code></pre> <p>for the original question:</p> <p>situation 1) IMHO for you...
1
2016-09-29T07:19:54Z
[ "python", "django", "mongodb", "django-rest-framework", "mongoengine" ]
apply function on groups of k elements of a pandas Series
39,763,436
<p>I have a pandas Series:</p> <pre><code>0 1 1 5 2 20 3 -1 </code></pre> <p>Lets say I want to apply <code>mean()</code> on every two elements, so I get something like this:</p> <pre><code>0 3.0 1 9.5 </code></pre> <p>Is there an elegant way to do this?</p>
4
2016-09-29T06:57:02Z
39,763,472
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>index</code> divide by <code>k=2</code>:</p> <pre><code>k = 2 print (s.index // k) Int64Index([0, 0, 1, 1], dtype='int64') print (s.groupby([s.index // k]).mean())...
3
2016-09-29T06:58:51Z
[ "python", "pandas", "group-by", "mean", "series" ]
apply function on groups of k elements of a pandas Series
39,763,436
<p>I have a pandas Series:</p> <pre><code>0 1 1 5 2 20 3 -1 </code></pre> <p>Lets say I want to apply <code>mean()</code> on every two elements, so I get something like this:</p> <pre><code>0 3.0 1 9.5 </code></pre> <p>Is there an elegant way to do this?</p>
4
2016-09-29T06:57:02Z
39,763,606
<p>If you are using this over large series and many times, you'll want to consider a fast approach. This solution uses all numpy functions and will be fast.</p> <p>Use <code>reshape</code> and construct new <code>pd.Series</code></p> <p>consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series...
2
2016-09-29T07:05:44Z
[ "python", "pandas", "group-by", "mean", "series" ]
apply function on groups of k elements of a pandas Series
39,763,436
<p>I have a pandas Series:</p> <pre><code>0 1 1 5 2 20 3 -1 </code></pre> <p>Lets say I want to apply <code>mean()</code> on every two elements, so I get something like this:</p> <pre><code>0 3.0 1 9.5 </code></pre> <p>Is there an elegant way to do this?</p>
4
2016-09-29T06:57:02Z
39,763,641
<p>You can do this:</p> <pre><code>(s.iloc[::2].values + s.iloc[1::2])/2 </code></pre> <p>if you want you can also reset the index afterwards, so you have 0, 1 as the index, using:</p> <pre><code>((s.iloc[::2].values + s.iloc[1::2])/2).reset_index(drop=True) </code></pre>
1
2016-09-29T07:07:57Z
[ "python", "pandas", "group-by", "mean", "series" ]
Scapy: How to manipulate Host in http header?
39,763,486
<p>I wrote this piece of code to get http header and set Host:</p> <pre><code>http_layer = packet.getlayer(http.HTTPRequest).fields http_layer['Host'] = "newHostName" return packet </code></pre> <p>After running the afforementioned code,the new host name has been set correctly, but the problem is that when I write th...
0
2016-09-29T06:59:29Z
39,806,000
<p>After all, found the answer. The key is that <code>scapy</code> firstly parses <code>HTTP Request</code> and shows the dict of its fields. So when we try to assign a new field like <code>Host</code>, it changes the <code>Host</code> which it has already parsed and does not change the original field value. So, this i...
0
2016-10-01T11:22:57Z
[ "python", "packet", "scapy" ]
rpy2, package 'outliers' functions not working
39,763,558
<p>I have a problem with almost all functions from R`s package: outliers. The "choosen one" function which working correctly is outliers</p> <pre><code>list_ = ['chisq.out.test','cochran.test', 'dixon.test', 'grubbs.test', 'outlier', 'qcochran'] y = some data without brackets like 0.0, 0.0, 0.0, 0.484166666...
0
2016-09-29T07:03:06Z
39,768,032
<p>In R, the "dot" can be used in variable names. It cannot in Python.</p> <p><code>importr</code> is trying to help with this as described here: <a href="http://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html" rel="nofollow">http://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html</a></p>
0
2016-09-29T10:38:41Z
[ "python", "rpy2", "outliers" ]
imp.load_source loads wrong module
39,763,626
<p>I have two supposedly identical systems. On both systems, I run the same software, but on one of the two it doesn't function correctly.</p> <p>I'm trying to run function in a user-supplied <code>.py</code> file. I've reduced this to the following basic code that reproduces the error:</p> <pre><code>import imp with...
0
2016-09-29T07:07:01Z
39,772,942
<p>The reason why it is failing is because I'm doing it wrong. The second argument to <code>load_source</code> should be the full path to the source file, not just to the directory containing it <a href="https://docs.python.org/2/library/imp.html#imp.load_source" rel="nofollow" title="Python 2.7.12 documentation">Pytho...
0
2016-09-29T14:22:16Z
[ "python", "python-2.7", "python-import" ]
Error in webdriver.Chrome() After updated my Ubuntu from 14.04 to 16.04
39,763,630
<p>I have recently updated my Ubuntu from 14.04 to 16.04 when I am trying to run the driver = webdriver.Chrome() </p> <pre><code>I am using the Python Selenium and getting the following error: File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 67, in __init__ desired_capabi...
0
2016-09-29T07:07:15Z
39,773,862
<p>That's an old version of chromedriver, first things first, download the latest chromedriver, add it to the system path.</p>
0
2016-09-29T15:04:28Z
[ "python", "ubuntu-16.04" ]
in learning data mining with python ch5 error
39,763,709
<p><strong>code:</strong></p> <pre><code>import os import pandas as pd data_folder = os.path.join(os.path.expanduser("~"),"data","Ads") data_filename = os.path.join(data_folder,"ad.data") def convert_number(x): try: return float(x) except ValueError: return np.nan from collections import defaul...
0
2016-09-29T07:11:51Z
39,766,654
<p>The data source you linked to contains <code>?</code> symbols - I presume these are missing values. I suggest to filter them during reading from csv stage, like so:</p> <pre><code>ads = pd.read_csv(data_filename,header=None,converters=converters, na_values='?') </code></pre> <p>You may find more info on how to dea...
0
2016-09-29T09:34:01Z
[ "python" ]
Python random sampling in multiple indices
39,764,092
<p>I have a data frame according to below:</p> <pre> id_1 id_2 value 1 0 1 1 1 2 1 2 3 2 0 4 2 1 1 3 0 5 3 1 1 4 0 5 4 1 1 4 2 6 4 3 7 11 0 8 11 1 14 13 0 10 13 1 9 </pre> <p>I would like to take o...
1
2016-09-29T07:32:30Z
39,764,476
<p>This samples one random per id:</p> <pre><code>for id in sorted(set(df["id_1"])): print(df[df["id_1"] == id].sample(1)) </code></pre> <p>PS:</p> <p>translated above solution using pythons list comprehension, returning a list of of indices:</p> <pre><code>idx = [df[df["id_1"] == val].sample(1).index[0] for va...
1
2016-09-29T07:54:41Z
[ "python", "sampling" ]
Python random sampling in multiple indices
39,764,092
<p>I have a data frame according to below:</p> <pre> id_1 id_2 value 1 0 1 1 1 2 1 2 3 2 0 4 2 1 1 3 0 5 3 1 1 4 0 5 4 1 1 4 2 6 4 3 7 11 0 8 11 1 14 13 0 10 13 1 9 </pre> <p>I would like to take o...
1
2016-09-29T07:32:30Z
39,764,555
<p>You can do this using vectorized functions (not loops) using </p> <pre><code>import numpy as np uniqued = df.id_1.reindex(np.random.permutation(df.index)).drop_duplicates() df.ix[np.random.choice(uniqued.index, 1, replace=False)] </code></pre> <p><code>uniqued</code> is created by a random shuffle + choice of a ...
1
2016-09-29T07:58:02Z
[ "python", "sampling" ]
Django grappelli change column width to full screen in admin interface
39,764,109
<p>I'm using django for the first time. I've experience with python but not with web development. Now I'm trying to design an admin page with grappelli. Only grappelli doesn't show the tables full screen (column width too small) and it looks horrible. Only a third of my screen is used. Is there a way to set the column ...
-1
2016-09-29T07:33:18Z
39,764,151
<p>Try <a href="http://stackoverflow.com/questions/12309788/how-to-fix-set-column-width-in-a-django-modeladmin-change-list-table-when-a-list">this one</a>, or <a href="https://www.sitepoint.com/community/t/changing-widths-of-django-admin-forms/34855/2" rel="nofollow">this one</a>. They are describing how to change the ...
0
2016-09-29T07:35:25Z
[ "python", "django", "dropdown", "django-grappelli" ]
Summing the values of one element of a dictionary based upon the values of another element
39,764,110
<p>Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.</p> <pre><code>[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] </code></pre> <p>This is the format (although there are m...
0
2016-09-29T07:33:21Z
39,764,210
<p>Here's a short code sample that puts the relevant sums into a dictionary. It simply iterates over each dictionary in the input list, adding the <code>area</code> values to the appropriate <code>elev</code> key.</p> <pre><code>from collections import defaultdict summed_dict = defaultdict(float) for tup in input_lis...
0
2016-09-29T07:38:55Z
[ "python", "dictionary" ]
Summing the values of one element of a dictionary based upon the values of another element
39,764,110
<p>Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.</p> <pre><code>[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] </code></pre> <p>This is the format (although there are m...
0
2016-09-29T07:33:21Z
39,764,249
<p>You can try:</p> <pre><code>&gt;&gt;&gt; l = [{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] &gt;&gt;&gt; added_dict = {} &gt;&gt;&gt; for i in l: if i['elev'] in added_dict: added_dict[i['elev']] += i['area'] else: added_dict[i['elev']] = i['ar...
0
2016-09-29T07:40:42Z
[ "python", "dictionary" ]
Summing the values of one element of a dictionary based upon the values of another element
39,764,110
<p>Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.</p> <pre><code>[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] </code></pre> <p>This is the format (although there are m...
0
2016-09-29T07:33:21Z
39,764,331
<p>Using a <code>defaultdict</code>, you don't need to the <code>if/else</code> statement:</p> <pre><code>from collections import defaultdict mylist = [{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] sumdict = defaultdict(float) for d in mylist: sumdict[d['elev']] += d.get('a...
1
2016-09-29T07:46:09Z
[ "python", "dictionary" ]
Summing the values of one element of a dictionary based upon the values of another element
39,764,110
<p>Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.</p> <pre><code>[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}] </code></pre> <p>This is the format (although there are m...
0
2016-09-29T07:33:21Z
39,764,420
<p>this is very easily achieved using pandas. Sample code:</p> <pre><code>import pandas as pd df = pd.DataFrame([{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]) </code></pre> <p>which gives the following dataframe:</p> <pre><code> area elev 0 3.523558 0.0 1 3.523558 ...
2
2016-09-29T07:51:16Z
[ "python", "dictionary" ]
How to get all objects in a Django model(Databse table) based on a filter using AngularJs
39,764,294
<p>Hi I have a Django model as below:</p> <pre><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class Journal(models.Model): name = models.CharField(max_length=120) created_by = models.ForeignKey(User, related_na...
0
2016-09-29T07:43:16Z
39,765,355
<p>To retrieve all Journal objects, you can create a view with <a href="http://www.django-rest-framework.org/" rel="nofollow">django REST framework</a> and on angular side simply create a <code>Service</code> and use <a href="https://docs.angularjs.org/api/ngResource/service/$resource" rel="nofollow"><code>$resource</c...
1
2016-09-29T08:36:22Z
[ "python", "angularjs", "django" ]
How to get all objects in a Django model(Databse table) based on a filter using AngularJs
39,764,294
<p>Hi I have a Django model as below:</p> <pre><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class Journal(models.Model): name = models.CharField(max_length=120) created_by = models.ForeignKey(User, related_na...
0
2016-09-29T07:43:16Z
39,765,559
<p>Try the this method on server side</p> <pre><code>import json from django.http import JsonResponse from django.views.generic View from .models import Journal class JSONResponseMixin(object): """ A mixin that can be used to render a JSON response. """ def render_to_json_response(self, context, **r...
1
2016-09-29T08:46:08Z
[ "python", "angularjs", "django" ]
Django Error - django.db.utils.DatabaseError: Data truncated for column 'applied' at row 1
39,764,318
<p>I am getting a weird issue when executing <code>python manage.py migrate</code>. </p> <p>Below is the error. </p> <blockquote> <p>django.db.utils.DatabaseError: Data truncated for column 'applied' at row 1</p> </blockquote> <p><a href="http://i.stack.imgur.com/fG00J.jpg" rel="nofollow"><img src="http://i.stack....
1
2016-09-29T07:45:23Z
39,766,959
<p>Solution of my problem is mentioned on the below URL, this is a bug with the latest version of Django. You need to change USE_TZ = False in settings.py</p> <p><a href="http://stackoverflow.com/questions/34716360/incorrect-datetime-value-when-setting-up-django-with-mysql">Incorrect datetime value when setting up Dja...
1
2016-09-29T09:47:45Z
[ "python", "django", "python-3.5" ]
Invisible unicode characters loaded to DB in python
39,764,520
<p>There are many questions and fixes for this but none seems to work for me. My problem is I am reading a file with strings and loading each line into DB.</p> <p>In file it is looking like normal text,while in DB it is read as a unicode space. I tried replacing it with a space and similar options but none worked.</p>...
0
2016-09-29T07:56:37Z
39,764,638
<p>Try this:</p> <p>This will remove <code>Unicode</code> character</p> <pre><code>&gt;&gt;&gt; s = "The abrupt departure" &gt;&gt;&gt; s = s.decode('unicode_escape').encode('ascii','ignore') &gt;&gt;&gt; s 'The abrupt departure' </code></pre> <p>Or, You can try with replace as you have tried. But you forget to re...
1
2016-09-29T08:02:33Z
[ "python", "mysql", "string", "unicode", "replace" ]
Invisible unicode characters loaded to DB in python
39,764,520
<p>There are many questions and fixes for this but none seems to work for me. My problem is I am reading a file with strings and loading each line into DB.</p> <p>In file it is looking like normal text,while in DB it is read as a unicode space. I tried replacing it with a space and similar options but none worked.</p>...
0
2016-09-29T07:56:37Z
39,765,157
<p>The point is strings are immutable, you need to assign the return value from <code>replace</code>:</p> <pre><code> s = s.replace('\xa0', ' ') s = s.replace('\xc2', ' ') </code></pre> <p>Also, don't use <code>str</code> as a variable name.</p>
1
2016-09-29T08:26:49Z
[ "python", "mysql", "string", "unicode", "replace" ]
Invisible unicode characters loaded to DB in python
39,764,520
<p>There are many questions and fixes for this but none seems to work for me. My problem is I am reading a file with strings and loading each line into DB.</p> <p>In file it is looking like normal text,while in DB it is read as a unicode space. I tried replacing it with a space and similar options but none worked.</p>...
0
2016-09-29T07:56:37Z
39,800,679
<p><code>C2A0</code> is a "NO-BREAK SPACE". <code>'Â '</code> is what you see if your <code>CHARATER SET</code> settings are inconsistent.</p> <p>Doing a <code>replace()</code> is merely masking the problem, and not helping when a different funny character comes into your table.</p> <p>Since you have not provided e...
1
2016-09-30T22:01:35Z
[ "python", "mysql", "string", "unicode", "replace" ]
How to read stream of a subprocess in python?
39,764,581
<p>I create a process with <code>subprocess.Popen</code> and get its <code>stdout</code>. I want to read content from <code>stdout</code> and print it out in another thread. Since my purpose it to make a an interactive program later, I cannot use <code>subprocess.communicate</code>.</p> <p>My basic requirement is: Onc...
-1
2016-09-29T07:59:20Z
39,766,920
<p>As cdarke mentioned. This program is suffered from buffering. However it is more like a bug in python 2.x. The logic is nothing wrong in the current program. </p> <p>To fix the issue, you have to reopen the stdout. Like the code below:</p> <pre><code>def thread_print_stream(out_stream): def helper(s): print ...
0
2016-09-29T09:45:44Z
[ "python", "multithreading", "subprocess" ]
"Densifying" very large sparse matrices by rearranging rows/columns
39,764,582
<p>I have a very large sparse matrix (240k*4.5k, ≤1% non-zero elements), which I would like to "densify" by rearranging its rows and columns in a way that the upper left region is enriched in non-zero elements as much as possible. (To make it more manageable and visually assessable.) I would prefer <code>scipy</code>...
3
2016-09-29T07:59:22Z
39,791,339
<p>It looks like you can already swap rows preserving sparsity so the missing part is the algorithm to sort the rows. So you need a function that gives you a "leftness" score. A heuristic that could work is the following:</p> <ol> <li>first get a mask of the non-zero elements (you don't care about the actual values, o...
1
2016-09-30T12:16:33Z
[ "python", "numpy", "matrix", "scipy", "scikit-learn" ]
"Densifying" very large sparse matrices by rearranging rows/columns
39,764,582
<p>I have a very large sparse matrix (240k*4.5k, ≤1% non-zero elements), which I would like to "densify" by rearranging its rows and columns in a way that the upper left region is enriched in non-zero elements as much as possible. (To make it more manageable and visually assessable.) I would prefer <code>scipy</code>...
3
2016-09-29T07:59:22Z
39,957,830
<p>I finally ended up with the solution below:<br> - First of all, based on the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html#scipy.sparse.lil_matrix" rel="nofollow">scipy documentation</a>, the LiL (linked list) format seems to be ideal for this sort of operations. (However ...
0
2016-10-10T12:01:45Z
[ "python", "numpy", "matrix", "scipy", "scikit-learn" ]
Merging 2 dataframe using similar columns
39,764,652
<p>I have 2 dataframe listed as follow</p> <p>df</p> <pre><code> Type Breed Common Color Other Color Behaviour Golden Big Gold White Fun Corgi Small Brown White Crazy Bulldog Medium Black Grey Strong </code></pre...
3
2016-09-29T08:03:04Z
39,764,707
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>print (pd.concat([df1[['Type','Breed','Behaviour']], df2[['Type','Breed','Behaviour']]], ignore_index=True)) Type Breed Behaviour 0 ...
4
2016-09-29T08:05:44Z
[ "python", "pandas", "multiple-columns", "intersection", "concat" ]
Merging 2 dataframe using similar columns
39,764,652
<p>I have 2 dataframe listed as follow</p> <p>df</p> <pre><code> Type Breed Common Color Other Color Behaviour Golden Big Gold White Fun Corgi Small Brown White Crazy Bulldog Medium Black Grey Strong </code></pre...
3
2016-09-29T08:03:04Z
39,764,866
<p>using <code>join</code> dropping columns that don't overlap</p> <pre><code>df1.T.join(df2.T, lsuffix='_').dropna().T.reset_index(drop=True) </code></pre> <p><a href="http://i.stack.imgur.com/wb6AL.png" rel="nofollow"><img src="http://i.stack.imgur.com/wb6AL.png" alt="enter image description here"></a></p>
4
2016-09-29T08:13:25Z
[ "python", "pandas", "multiple-columns", "intersection", "concat" ]
Template doesnot exist error in Django
39,764,739
<p>Am developing an angular frontend and Django backend app.I don't know where i am going wrong but Django cant seem to locate the template and displays a template doesn't exist message.The project directory looks like this.The backend server is in the "django project" folder</p> <p><a href="http://i.stack.imgur.com/...
0
2016-09-29T08:07:10Z
39,766,897
<p>I changed template DIRS setting to point to 'C:/downloads/mysite/frontend/' and also the template name to point to "/app/index.html".app is a folder inside frontend.</p>
0
2016-09-29T09:44:45Z
[ "python", "django" ]
Linear Programming with Anaconda
39,764,740
<p>I have installed Anaconda on my windows 10 and I am using it for Python. I have a class in Mathematical optimization and need a good package for basic LP. <strong>Is there a "pre-installed" package that is good for LP in Anaconda, that I can just import to my python file, or do I have to install packages?</strong> I...
0
2016-09-29T08:07:18Z
39,764,865
<p>If you wish to install PuLP on top of Anaconda on Windows it looks like you need to run:</p> <blockquote> <p>pip install pulp</p> </blockquote> <p>See pulp <a href="https://pythonhosted.org/PuLP/main/installing_pulp_at_home.html" rel="nofollow">docs</a></p>
0
2016-09-29T08:13:18Z
[ "python", "python-3.x", "anaconda", "linear-programming" ]
Python: How to convert Numpy array item value type to array with this value?
39,764,773
<p>What is the best way to convert such ndarray:</p> <pre><code>[[1,2,3], [4,5,6]] </code></pre> <p>to the:</p> <pre><code>[[[1],[2],[3]], [[4],[5],[6]]] </code></pre> <p>just wrap each value to array</p>
2
2016-09-29T08:09:03Z
39,764,823
<p>You can introduce a new axis with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>np.newaxis/None</code></a> at the end, like so -</p> <pre><code>arr[...,None] </code></pre> <p>Sample run -</p> <pre><code>In [6]: arr = np.array([[1,2,3], [4,5,6]])...
3
2016-09-29T08:11:10Z
[ "python", "arrays", "numpy" ]
Python: How to convert Numpy array item value type to array with this value?
39,764,773
<p>What is the best way to convert such ndarray:</p> <pre><code>[[1,2,3], [4,5,6]] </code></pre> <p>to the:</p> <pre><code>[[[1],[2],[3]], [[4],[5],[6]]] </code></pre> <p>just wrap each value to array</p>
2
2016-09-29T08:09:03Z
39,764,915
<p>You can do it by recursively exploring the list of lists:</p> <pre><code>def wrap_values(list_of_lists): if isinstance(list_of_lists, list): return [wrap_values(el) for _,el in enumerate(list_of_lists)] else: return [list_of_lists] xx = [[1,2,3], [4,5,6]] yy = wrap_values(xx) # [[[1], [2...
0
2016-09-29T08:15:37Z
[ "python", "arrays", "numpy" ]
error: (-215) _src.type() == CV_8UC1 in function equalizeHist when trying to equalize a float64 image
39,764,885
<p>I'm trying to equalize a 1 one channel image like so:</p> <pre><code>img = cv2.equalizeHist(img) </code></pre> <p>But since it's a float64 img, I get the following error:</p> <blockquote> <p>error: (-215) _src.type() == CV_8UC1 in function equalizeHist</p> </blockquote> <p>How do I go about this?</p>
0
2016-09-29T08:14:19Z
39,766,080
<p>The function equalizeHist is histogram equalization of images and only implemented for CV_8UC1 type, which is a single channel 8 bit unsigned integral type.</p> <p>To convert your image to this type you can use the function <code>convertTo</code> with the target type (must be the same number of channels).</p> <p>M...
0
2016-09-29T09:09:49Z
[ "python", "opencv", "numpy" ]
Aligning LaTeX ticklabels in Matplotlib
39,764,959
<p>I have a simple Matplotlib plot with LaTeX ticklabels. I'd like these to be centre-aligned so they all look even, but even with <code>va='center'</code> they appear to be at different vertical locations:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl # Some Matplotlib se...
0
2016-09-29T08:17:34Z
39,765,819
<p>Try using the alignment keyword <code>va='baseline'</code> for the vertical alignment. This aligns the text on the baseline, meaning the bottom line of all letters without descender. Theoretically all πs should line up nicely. </p> <pre><code>ax.set_xticklabels((r'$-\pi$', r'$-\pi/2$', '0', r'$...
0
2016-09-29T08:57:53Z
[ "python", "matplotlib" ]
mpi4py compilation error on a Suse system
39,764,986
<p>After I compile the mpi4py with the openmpi from the server I get a runtime error.</p> <pre><code> OS: SuSe GCC: 4.8.5 OpenMPI: 1.10.1 HDF5: 1.8.11 mpi4py: 2.0.0 Python: 2.7.9 </code></pre> <p><strong>Environment Settings:</strong> I use virtualenv (no admin permission of the server)</p> <pre><code>(ENV) use...
0
2016-09-29T08:18:37Z
39,793,296
<p>See: <a href="https://bitbucket.org/mpi4py/mpi4py/issues/52/mpi4py-compilation-error" rel="nofollow">https://bitbucket.org/mpi4py/mpi4py/issues/52/mpi4py-compilation-error</a></p> <p>It seems the issue was not because of an mpi4py bug but from the psm transport layer from the OpenMPI</p> <p>In my case setting </p...
0
2016-09-30T13:59:27Z
[ "python", "openmpi", "mpi4py" ]
Python: writing a text file with a lot of variables
39,765,047
<p>I need to create (from Python code) a text file with in each line some 50 variables, separated by comm's. I take the canonical way to be output.write ("{},{},{},{},{},{},{},{},{},{}, ... \n".format(v,v,v,v,... But that will be hard to read and difficult to maintain with such a lot of variables. Any other suggest...
0
2016-09-29T08:22:01Z
39,765,304
<h2>Using lists</h2> <p>When reaching a handful of variables that are related to each other, it is common to use a <code>list</code> or a <code>dict</code>. If you create a list:</p> <pre><code>myrow = [] myrow.append(v1) ... </code></pre> <p>This also allows for easier looping over each value. Once you have done th...
0
2016-09-29T08:34:01Z
[ "python", "csv", "file-writing" ]
Python: writing a text file with a lot of variables
39,765,047
<p>I need to create (from Python code) a text file with in each line some 50 variables, separated by comm's. I take the canonical way to be output.write ("{},{},{},{},{},{},{},{},{},{}, ... \n".format(v,v,v,v,... But that will be hard to read and difficult to maintain with such a lot of variables. Any other suggest...
0
2016-09-29T08:22:01Z
39,767,093
<p>If you can sort of your variables, you could use locals().</p> <p>for example:</p> <p>I set three variables:</p> <pre><code>var1 = 'xx' var2 = 'yy' var3 = 'zz' </code></pre> <p>and I can sort of them by sorted().</p> <pre><code>def sort(x): if len(x) != 4: return '99' else: return x[-1] ...
0
2016-09-29T09:54:46Z
[ "python", "csv", "file-writing" ]
Can I use np.arange with lists as my inputs?
39,765,093
<p>The relevant excerpt of my code is as follows:</p> <pre><code>import numpy as np def create_function(duration, start, stop): rates = np.linspace(start, stop, duration*1000) return rates def generate_spikes(duration, start, stop): rates = [create_function(duration, start, stop)] array = [np.arange(...
0
2016-09-29T08:24:10Z
39,765,303
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> there for efficiency purposes -</p> <pre><code>(a + (b[:,None] * a)).ravel('F') </code></pre> <p>Sample run -</p> <pre><code>In [52]: a Out[52]: array([1, 2, 3, 4]) In [53]: b Out[53]:...
1
2016-09-29T08:33:59Z
[ "python", "python-3.x", "numpy" ]
Altering packets on the fly with scapy as a MITM
39,765,107
<p>Assuming I managed to be in the middle of the communication between a client and a server (let's say that I open up a hotspot and cause the client to connect to the server only through my machine).</p> <p>How can I alter packets that my client sends and receives without interrupting my own communication with other ...
1
2016-09-29T08:24:47Z
39,800,766
<p>You can use <a href="http://www.netfilter.org/projects/libnetfilter_queue/doxygen/" rel="nofollow">NFQUEUE</a> which has <a href="https://pypi.python.org/pypi/NetfilterQueue" rel="nofollow">python bindings</a>.</p> <p>NFQUEUE is a userspace queue that is a valid iptables target. You can redirect some traffic to the...
1
2016-09-30T22:09:42Z
[ "python", "linux", "iptables", "scapy", "man-in-the-middle" ]
Google Task Queue REST pull returning 500 occasionally
39,765,136
<p>I have Python a process leasing tasks from the <a href="https://cloud.google.com/appengine/docs/python/taskqueue/rest/" rel="nofollow">Google TaskQueue REST API</a> every second in the unlimited loop:</p> <pre><code>credentials = GoogleCredentials.get_application_default() task_api = googleapiclient.discovery.build...
1
2016-09-29T08:26:00Z
39,792,576
<p>Since the @DalmTo has just answered in comments, I sum up his answers and add the Python solution.</p> <p>The Google 5xx backed error is flood protection and Google recommends to implement <a href="https://developers.google.com/drive/v3/web/handle-errors#500_backend_error" rel="nofollow">exponential backoff</a>. De...
1
2016-09-30T13:21:02Z
[ "python", "google-app-engine", "google-compute-engine", "task-queue" ]
Display values that does not end with ".0" Python Pandas
39,765,264
<p>I have a float column that contains <code>NaN</code> values and float values. How do i filter out those values that does not end with <code>.0</code>?</p> <p>For example:</p> <pre><code>Col1 0.7 1.0 1.1 9.0 9.5 NaN </code></pre> <p>Desire result will be:</p> <pre><code>Col1 0.7 1.1 9.2 </code></pre>
3
2016-09-29T08:31:56Z
39,765,337
<p>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>#convert to string and compare last value print ((df.Col1.astype(str).str[-1] != '0') &amp; (df.Col1.notnull())) 0 True 1 False 2 True 3 Fal...
3
2016-09-29T08:35:23Z
[ "python", "pandas", "indexing", "condition", null ]
Display values that does not end with ".0" Python Pandas
39,765,264
<p>I have a float column that contains <code>NaN</code> values and float values. How do i filter out those values that does not end with <code>.0</code>?</p> <p>For example:</p> <pre><code>Col1 0.7 1.0 1.1 9.0 9.5 NaN </code></pre> <p>Desire result will be:</p> <pre><code>Col1 0.7 1.1 9.2 </code></pre>
3
2016-09-29T08:31:56Z
39,765,379
<p>use <code>//</code> division</p> <pre><code>df[df.Col1 // 1 != df.Col1].dropna() </code></pre> <p><a href="http://i.stack.imgur.com/ZhlRy.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZhlRy.png" alt="enter image description here"></a></p>
3
2016-09-29T08:37:25Z
[ "python", "pandas", "indexing", "condition", null ]
Display values that does not end with ".0" Python Pandas
39,765,264
<p>I have a float column that contains <code>NaN</code> values and float values. How do i filter out those values that does not end with <code>.0</code>?</p> <p>For example:</p> <pre><code>Col1 0.7 1.0 1.1 9.0 9.5 NaN </code></pre> <p>Desire result will be:</p> <pre><code>Col1 0.7 1.1 9.2 </code></pre>
3
2016-09-29T08:31:56Z
39,765,388
<p>Another method is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mod.html#pandas.Series.mod" rel="nofollow"><code>mod(1)</code></a> to calculate the modulo with 1:</p> <pre><code>In [60]: df[df['Col1'].mod(1) &gt; 0].dropna() Out[60]: Col1 0 0.7 2 1.1 4 9.5 </code></pr...
2
2016-09-29T08:38:02Z
[ "python", "pandas", "indexing", "condition", null ]
Elasticsearch filtering for the same range brings back different amount of results
39,765,346
<p>I want to perform the following query</p> <pre><code>SELECT * FROM logs WHERE dst != "-" AND @timestamp &gt; "a date before" AND @timestamp &lt; "now" </code></pre> <p>I use python elasticsearch sdk, and formed two queries for testing</p> <pre><code>from elasticsearch import Elasticsearch from datetime import d...
0
2016-09-29T08:35:56Z
39,765,809
<p>You can try <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/logging.html" rel="nofollow">logging</a> to see what is really happening with your elastic search queries.</p>
1
2016-09-29T08:57:32Z
[ "python", "elasticsearch" ]
Adding an extension in Sphinx (Python Documentation Generator) configuration file
39,765,520
<p>I want to use Sphinx as a documentation generator. When I try to run the <strong>make html</strong> command, I have the following error : </p> <p><code>Extension error: Could not import extension sphinxcontrib.httpdomain (exception: No module named sphinxcontrib.httpdomain) make: *** [html] Error 1</code></p> <p>I...
0
2016-09-29T08:44:06Z
39,770,308
<p>The configuration is in the <code>source</code> folder of your Sphinx project. It is named <code>conf.py</code> and contains an <code>extensions</code> option which should look like this:</p> <pre><code># Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sph...
0
2016-09-29T12:26:04Z
[ "python", "osx", "python-sphinx" ]
Variable not defined PYTHON 3.5.2
39,765,529
<pre><code>def GameMode():#creates a function with name of gamemode global wrong_answer_1 for keys,values in keywords.items():#checks for the right answer if keys == code:#if the keys equal to the code value keyword_c = values global keyword_c for keys,values in definition.it...
-1
2016-09-29T08:44:20Z
39,765,684
<p>Why didn't you want to create a class with variables:</p> <pre><code>self.keyword_c = '' self.definition_c = '' self.wrong_answer_1 = '' self.wrong_answer_2 = '' </code></pre> <p>so variables would be global (if every method and variable is inside class) and with your method:</p> <pre><code>def GameMode(self):#cr...
0
2016-09-29T08:52:32Z
[ "python", "variables", "global-scope", "python-3.5.2" ]
Variable not defined PYTHON 3.5.2
39,765,529
<pre><code>def GameMode():#creates a function with name of gamemode global wrong_answer_1 for keys,values in keywords.items():#checks for the right answer if keys == code:#if the keys equal to the code value keyword_c = values global keyword_c for keys,values in definition.it...
-1
2016-09-29T08:44:20Z
39,765,846
<p>I am not sure what your function is supposed to be doing; it is hard to guess with all the syntax errors, but the following fixes the syntax errors, using a single global at the top of the function for everything which is not defined within the function.</p> <pre><code>def GameMode():#creates a function with name o...
0
2016-09-29T08:59:39Z
[ "python", "variables", "global-scope", "python-3.5.2" ]
Form validation in another route Flask
39,765,548
<p>I have a flask wtform. I am able to validate the form in a route where it is instantiated. But I want to validate it from another route. Without using session variable, Is there any other way by which I can access the form object from the other route?</p> <p><strong>form_class.py</strong></p> <pre><code>class Frui...
1
2016-09-29T08:45:22Z
39,857,330
<p>You have to call the Fruit class with request.form</p> <pre><code>@app.route('/fruit_submit', methods = ['GET', 'POST']) def fruit_submit(): print Fruit(request.form) if Fruit(request.form).validate_on_submit(): return render_template("output.html") </code></pre>
0
2016-10-04T16:22:20Z
[ "python", "flask", "flask-wtforms" ]
Python to receive huge string as argument from rabbitmq
39,765,673
<p>On Raspberry 3 I run a Rabbit-Mq listener.py that receives a large string (json) consisting of 14000 key/value pairs. The listener.py script will grab this string and pass it along to another script(database.py) that will encode it back to json(python dict object), parse it and store the values to a Mariadb database...
0
2016-09-29T08:52:04Z
39,766,722
<p>A simple way would be to use multiprocessing.connection with its <a href="https://docs.python.org/3/library/multiprocessing.html?highlight=multiprocessing#module-multiprocessing.connection" rel="nofollow">Listener and Client</a>. These methods use pickle internally.</p>
1
2016-09-29T09:36:53Z
[ "python", "json", "rabbitmq", "pickle" ]
Blaze with Scikit Learn K-Means
39,765,738
<p>I am trying to fit Blaze data object to scikit kmeans function.</p> <pre><code>from blaze import * from sklearn.cluster import KMeans data_numeric = Data('data.csv') data_cluster = KMeans(n_clusters=5) data_cluster.fit(data_numeric) </code></pre> <p>Data Sample:</p> <pre><code>A B C 1 32 34 5 57 92 89 67 21 <...
10
2016-09-29T08:54:47Z
39,892,096
<p>I would suggest that you choose the number of clusters (K) to be much smaller than the number of training examples you have in your data set. It is not right to run the K-Means algorithm when the number of clusters you desire is greater than or equal to the number of training examples. The error occurs when you try ...
1
2016-10-06T09:14:55Z
[ "python", "scikit-learn", "blaze" ]
Blaze with Scikit Learn K-Means
39,765,738
<p>I am trying to fit Blaze data object to scikit kmeans function.</p> <pre><code>from blaze import * from sklearn.cluster import KMeans data_numeric = Data('data.csv') data_cluster = KMeans(n_clusters=5) data_cluster.fit(data_numeric) </code></pre> <p>Data Sample:</p> <pre><code>A B C 1 32 34 5 57 92 89 67 21 <...
10
2016-09-29T08:54:47Z
39,920,176
<p>I think you need to convert your pandas dataframe into an numpy array before you fit. </p> <pre><code>from blaze import * import numpy from sklearn.cluster import KMeans data_numeric = numpy.array(data('data.csv')) data_cluster = KMeans(n_clusters=5) data_cluster.fit(data_numeric) </code></pre>
5
2016-10-07T14:53:30Z
[ "python", "scikit-learn", "blaze" ]
Blaze with Scikit Learn K-Means
39,765,738
<p>I am trying to fit Blaze data object to scikit kmeans function.</p> <pre><code>from blaze import * from sklearn.cluster import KMeans data_numeric = Data('data.csv') data_cluster = KMeans(n_clusters=5) data_cluster.fit(data_numeric) </code></pre> <p>Data Sample:</p> <pre><code>A B C 1 32 34 5 57 92 89 67 21 <...
10
2016-09-29T08:54:47Z
39,952,326
<p><code>sklearn.cluster.KMeans</code> don't support input data with type <code>blaze.interactive._Data</code> which is the type of data_numeric in your code.</p> <p>You can use <code>data_cluster.fit(data_numeric.peek())</code> to fit the transferred data_numeric with type <code>DataFrame</code> supported by <code>sk...
2
2016-10-10T06:22:19Z
[ "python", "scikit-learn", "blaze" ]
Blaze with Scikit Learn K-Means
39,765,738
<p>I am trying to fit Blaze data object to scikit kmeans function.</p> <pre><code>from blaze import * from sklearn.cluster import KMeans data_numeric = Data('data.csv') data_cluster = KMeans(n_clusters=5) data_cluster.fit(data_numeric) </code></pre> <p>Data Sample:</p> <pre><code>A B C 1 32 34 5 57 92 89 67 21 <...
10
2016-09-29T08:54:47Z
39,991,875
<p>Yes,before you fit ,you must need to convert your pandas dataframe into an numpy array,now its works fine...i think @aberger already answered .</p> <p>thank you!</p>
0
2016-10-12T06:30:07Z
[ "python", "scikit-learn", "blaze" ]
"from" import works differently
39,765,779
<p>I have this code in my Python code (<code>settings.py</code> is located in the <code>PROJECT</code> dir):</p> <pre><code>import PROJECT.settings ... if PROJECT.settings.BASE_DIR: ... </code></pre> <p>which works fine. I'd say I could rewrite to this:</p> <pre><code>from PROJECT import settings ... if settings....
0
2016-09-29T08:56:21Z
39,765,830
<p>The <code>from parent import name</code> format first looks for names in the <code>module</code> namespace (set in <code>__init__.py</code> or anything that added that name to the <code>parent</code> module).</p> <p>In your case, the <code>__init__.py</code> file in <code>PROJECT</code> has set <code>settings</code...
3
2016-09-29T08:58:57Z
[ "python" ]
Get the full name of a nested class
39,765,903
<p>Given a nested class <code>B</code>:</p> <pre><code>class A: class B: def __init__(self): pass ab = A.B() </code></pre> <p>How can I get the full name of the class for <code>ab</code>? I'd expect a result like <code>A.B</code>. </p>
0
2016-09-29T09:02:02Z
39,766,043
<p>You could get the fully qualified name, <a href="https://docs.python.org/3/library/stdtypes.html#definition.__qualname__" rel="nofollow"><code>__qualname__</code></a>, of its <a href="https://docs.python.org/3/library/stdtypes.html#instance.__class__" rel="nofollow"><code>__class__</code></a>:</p> <pre><code>&gt;&g...
2
2016-09-29T09:08:25Z
[ "python", "class", "python-3.x" ]
How to reduce Django class based view boilerplate
39,765,907
<p>I really hate boilerplate. However, I can't deny that code such as the following is a huge benefit. So my question, what does one do in Python to make up for the fact that it doesn't come with a macro (template) pre-processor?</p> <p>One idea would be to write a factory function, but I'll willingly admit that I don...
0
2016-09-29T09:02:19Z
39,768,951
<p>Python and Django are awesome.</p> <p>I read and re-read the (quite short) documentation of the 3-argument form of <code>type</code> that you use to dynamically create classes (<a href="https://docs.python.org/3/library/functions.html#type" rel="nofollow">https://docs.python.org/3/library/functions.html#type</a>). ...
1
2016-09-29T11:24:39Z
[ "python", "django", "python-3.x", "boilerplate" ]
Web scraping asian language sites with Python
39,765,939
<p>Not very familiar with the Python ecosystem, or with web scraping generally. So I'm trying to scrape content from a Chinese language site. </p> <pre><code>from bs4 import BeautifulSoup import requests r = requests.get("https://www.baidu.com/") r.encoding = 'utf-8' text = r.text soup = BeautifulSoup(text.encode('...
0
2016-09-29T09:03:48Z
39,766,826
<p>I think you don't need to specify the encoding for request. since the r.text has do the coding-transform work and r.content is the raw data.</p> <p>see the documents:</p> <pre><code> | text | Content of the response, in unicode. | | If Response.encoding is None, encoding will be guessed using ...
-1
2016-09-29T09:41:47Z
[ "python", "web-scraping", "beautifulsoup" ]
Astroquery VizieR UCAC4 full download
39,765,998
<p>I would like to have a local (offline) ASCII version of <strong>UCAC4</strong> star catalogue in order to have an isolated work environment (no internet).</p> <p>I am having issues trying to retrieve this specific <em>full</em> catalog. Downloading small parts is pretty straightforward using <strong>topcat</strong>...
2
2016-09-29T09:06:22Z
39,796,905
<p>To download large data sets, you need to increase the <code>ROW_LIMIT</code>. The default is only 50 because we wanted to limit the load on the vizier servers unless users know what they're doing.</p> <pre><code>from astroquery.vizier import Vizier Vizier.ROW_LIMIT = 100000000000 </code></pre>
2
2016-09-30T17:26:09Z
[ "python", "astronomy", "astropy" ]
Astroquery VizieR UCAC4 full download
39,765,998
<p>I would like to have a local (offline) ASCII version of <strong>UCAC4</strong> star catalogue in order to have an isolated work environment (no internet).</p> <p>I am having issues trying to retrieve this specific <em>full</em> catalog. Downloading small parts is pretty straightforward using <strong>topcat</strong>...
2
2016-09-29T09:06:22Z
39,874,130
<p>Fastest solution : get the <a href="http://vizier.u-strasbg.fr/vizier/doc/cdsclient.html" rel="nofollow">cdsclient</a> package. Run the finducac4 program with -whole option, for example : finducac4 -whole -m 115000000 > myUcac4.dat</p>
1
2016-10-05T12:35:19Z
[ "python", "astronomy", "astropy" ]
Pandas: adding new column to existing Data Frame for grouping purposes
39,766,141
<p>I have a <code>pandas</code> Data Frame consisting of 2000 rows x 8 columns. I want to be able to group the first 4 columns together, as well as the other 4, but I can't figure out how. The purpose is to create a categorical bar plot, with colors assigned according to C1=C5, C2=C6, and so forth.</p> <p>My Data Fram...
2
2016-09-29T09:12:45Z
39,766,297
<p>use <code>pd.concat</code></p> <pre><code>pd.concat([df.iloc[:, :4], df.iloc[:, 4:]], axis=1, keys=['first4', 'second4']) </code></pre> <p><a href="http://i.stack.imgur.com/8Fb5d.png" rel="nofollow"><img src="http://i.stack.imgur.com/8Fb5d.png" alt="enter image description here"></a></p>
1
2016-09-29T09:19:14Z
[ "python", "pandas", "dataframe", "grouping", "bar-chart" ]
Pandas: adding new column to existing Data Frame for grouping purposes
39,766,141
<p>I have a <code>pandas</code> Data Frame consisting of 2000 rows x 8 columns. I want to be able to group the first 4 columns together, as well as the other 4, but I can't figure out how. The purpose is to create a categorical bar plot, with colors assigned according to C1=C5, C2=C6, and so forth.</p> <p>My Data Fram...
2
2016-09-29T09:12:45Z
39,766,458
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="nofollow"><code>MultiIndex.from_arrays</code></a>:</p> <pre><code>df.columns = pd.MultiIndex.from_arrays([['a'] * 4 + ['b'] * 4 , df.columns]) print (df) a b C1 C2 C...
3
2016-09-29T09:25:15Z
[ "python", "pandas", "dataframe", "grouping", "bar-chart" ]
How do I display floats as currency with negative sign before currency
39,766,218
<p>consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series([-1.23, 4.56]) s 0 -1.23 1 4.56 dtype: float64 </code></pre> <p>I can format floats with pandas <code>display.float_format</code> option</p> <pre><code>with pd.option_context('display.float_format', '${:,.2f}'.format): print...
4
2016-09-29T09:15:53Z
39,766,887
<p>You can substitute the formatting function with your own. Below is just a demo of how it works, you can tune it to your own needs:</p> <pre><code>def formatfunc(*args, **kwargs): value = args[0] if value &gt;= 0: return '${:,.2f}'.format(value) else: return '-${:,.2f}'.format(abs(value))...
3
2016-09-29T09:44:28Z
[ "python", "pandas" ]
CNTK tutorial:"Hands-On Lab: Image recognition with Convolutional Networks, Batch Normalization, and Residual Nets" python problems
39,766,242
<p>I am trying to follow this tutorial: <a href="https://github.com/Microsoft/CNTK/wiki/Hands-On-Labs-Image-Recognition" rel="nofollow">https://github.com/Microsoft/CNTK/wiki/Hands-On-Labs-Image-Recognition</a> I am now at the point where Frank is saying:” Please execute the following two Python scripts which you wi...
0
2016-09-29T09:16:34Z
39,776,802
<p>You are using Python 3.+ version. Try it with Python 2.7, and it should be ok.</p>
1
2016-09-29T17:43:55Z
[ "python", "windows", "cntk" ]
Use output of a bash command as an input to environment variable in VSCode
39,766,323
<p>In VSCode launch configuration for python, I set environment variables using the env element, like this:</p> <pre><code>"env": { "SOME_VARIABLE" : "SOME_VALUE" } </code></pre> <p>I want to set the value of this environment variable to the result of a bash command, like it is done in command line this w...
0
2016-09-29T09:20:11Z
39,806,049
<p>Hisham, I'm the author of the extension. Unfortunately such a feature isn't supported at this state.</p>
1
2016-10-01T11:27:52Z
[ "python", "vscode", "vscode-extensions" ]
Return all data from a loop (multiple returns so the page gets overwritten)
39,766,344
<p>I'm working on an API for an app, but I want to output multiple json objects from my sql query but if I use multiple returns the page gets overwritten.</p> <p>My code is :</p> <pre><code>@app.route('/api/location') @support_jsonp def get_locations(): d = {} for i, row in enumerate(locations): l...
0
2016-09-29T09:21:09Z
39,767,002
<p>I had to use stream_with_context &amp; Response so I could yield it</p> <p>example:</p> <pre><code>@app.route('/api/location') @support_jsonp def get_locations(): def generate(): d = {} for i, row in enumerate(locations): l = [] for col in rang...
0
2016-09-29T09:49:58Z
[ "python", "flask" ]
How to compare HTTP headers with time fields in Python?
39,766,497
<p>I am using Python to construct a proxy server as an exercise and I want to compare two different strings of time received from a server. For example,</p> <pre><code>Date: Sun, 24 Nov 2013 18:34:30 GMT Expires: Sat, 23 Nov 2013 18:34:30 GMT </code></pre> <p>How can I compare whether the expiry time is earlier than...
0
2016-09-29T09:26:53Z
39,766,991
<p>Convert each of the strings to a timestamp and compare these, for example as follows:</p> <pre><code>from datetime import datetime date1 = "Date: Sun, 24 Nov 2013 18:34:30 GMT" date2 = "Expires: Sat, 23 Nov 2013 18:34:30 GMT" format = "%a, %d %b %Y %H:%M:%S %Z" if datetime.strptime(date1, "Date: " + format) &...
0
2016-09-29T09:49:23Z
[ "python", "time", "http-headers", "compare", "http-proxy" ]
Running a Docker image in PyCharm causes "Invalid volume specification"
39,766,499
<p>I am trying to run a project based on a Docker Image (Tensorflow, following instructions from <a href="http://www.netinstructions.com/how-to-install-and-run-tensorflow-on-a-windows-pc/" rel="nofollow">this tutorial</a>) as described in <a href="https://blog.jetbrains.com/pycharm/2015/12/using-docker-in-pycharm/" rel...
0
2016-09-29T09:26:56Z
39,766,501
<p>This is a Windows Linux path problem. To solve it, change project paths to the Docker file to <code>/c/Path-to-project/Project-name</code> (with a lower case c and forward slashes) in order to solve this problem. Inspired by <a href="https://blog.jetbrains.com/pycharm/2016/06/pycharm-2016-2-eap-4-build-162-1120/" re...
0
2016-09-29T09:26:56Z
[ "python", "windows", "docker", "tensorflow", "pycharm" ]
Running a Docker image in PyCharm causes "Invalid volume specification"
39,766,499
<p>I am trying to run a project based on a Docker Image (Tensorflow, following instructions from <a href="http://www.netinstructions.com/how-to-install-and-run-tensorflow-on-a-windows-pc/" rel="nofollow">this tutorial</a>) as described in <a href="https://blog.jetbrains.com/pycharm/2015/12/using-docker-in-pycharm/" rel...
0
2016-09-29T09:26:56Z
39,968,174
<p>I solved this problem as follows:</p> <ol> <li>Go to: <code>File -&gt; Settings -&gt; Project -&gt; Project Interpreter -&gt; Your docker interpreter -&gt; Path mappings</code>;</li> <li>Add row: <code>{'Local path': 'C:', 'Remote path': '/c'}</code> (replace to your drive with project; if you use this interpeter f...
0
2016-10-10T23:17:29Z
[ "python", "windows", "docker", "tensorflow", "pycharm" ]
Get element closest to cluster centroid
39,766,593
<p>After clustering a distance matrix with <code>scipy.cluster.hierarchy.linkage</code>, and assigning each sample to a cluster using <code>scipy.cluster.hierarchy.cut_tree</code>, I would like to extract one element out of each cluster, which is the closest to that cluster's centroid.</p> <ul> <li>I would be the happ...
0
2016-09-29T09:30:58Z
39,767,308
<p>Nearest neighbours are most efficiently computed using KD-Trees. E.g.:</p> <pre><code>from scipy.spatial import cKDTree def find_k_closest(centroids, data, k=1, distance_norm=2): """ Arguments: ---------- centroids: (M, d) ndarray M - number of clusters d - number of dat...
1
2016-09-29T10:04:45Z
[ "python", "numpy", "scipy", "scikit-learn" ]
Get element closest to cluster centroid
39,766,593
<p>After clustering a distance matrix with <code>scipy.cluster.hierarchy.linkage</code>, and assigning each sample to a cluster using <code>scipy.cluster.hierarchy.cut_tree</code>, I would like to extract one element out of each cluster, which is the closest to that cluster's centroid.</p> <ul> <li>I would be the happ...
0
2016-09-29T09:30:58Z
39,870,085
<p><a href="http://stackoverflow.com/users/2912349/paul">Paul</a>'s solution above works well for multidimensional arrays. In the more specific case, where you have a distance matrix <code>dm</code>, in which the distances are calculated in a "non-trivial" way (<em>e.g.</em> each pair objects is aligned in 3D first, th...
0
2016-10-05T09:20:51Z
[ "python", "numpy", "scipy", "scikit-learn" ]
Rotating character and sprite wall
39,766,665
<p>I have a sprite that represents my character. This sprite rotates every frame according to my mouse position which in turn makes it so my rectangle gets bigger and smaller depending on where the mouse is. </p> <p>Basically what I want is to make it so my sprite (<code>Character</code>) doesn't go into the sprite ...
1
2016-09-29T09:34:18Z
39,811,728
<p>It all depends on how your sprite looks and how you want the result to be. There are 3 different types of collision detection I believe could work in your scenario.</p> <h2>Keeping your rect from resizing</h2> <p>Since the image is getting larger when you rotate it, you could compensate by just removing the extra ...
2
2016-10-01T21:42:57Z
[ "python", "python-2.7", "pygame", "sprite" ]
Add custom http header in RedirectView
39,766,817
<p>I want to add the http header but it does not work. I'm trying to test solve by using the print, but it appears nothing</p> <p>This is my code but not works:</p> <pre><code>class MyRedirectView(RedirectView): def head(self, *args, **kwargs): response = HttpResponse() response['X-Robots-Tag'] =...
1
2016-09-29T09:41:27Z
39,767,133
<p>What you have done here is to override the <code>head</code> method. Which is only used when a HTTP request of the type HEAD is made to your url. You should override the <code>get</code> method or better still the dispatch method instead.</p> <pre><code>class MyRedirectView(RedirectView): def dispatch(self, *a...
1
2016-09-29T09:56:18Z
[ "python", "django", "http-headers", "django-class-based-views" ]
How to use num2date/ date2num with Tkinter mainloop()
39,766,830
<p>I have this code inside a tkinter <code>mainloop()</code>:</p> <pre><code>self.raw_start_date = num2date(date2num(dt.datetime.strptime(self.end_date, "%Y-%m-%d")) - self.period) self.start_date = self.raw_start_date.strftime("%Y-%m-%d") </code></pre> <p>I get the following error:</p> <blockquote> <p>File "D:\Py...
-1
2016-09-29T09:42:01Z
39,811,563
<p>This is an artifact of subclassing <code>tkinter.Tk</code> and overriding the <code>__init__</code> method without ever calling <code>Tk.__init__</code>:</p> <pre><code>import tkinter class Application(tkinter.Tk): def __init__(self): "do out stuff, forget to call Tk.__init__(self) !" pass ap...
0
2016-10-01T21:19:29Z
[ "python", "tkinter", "tail-recursion" ]
How To Fix "TypeError: 'NoneType' object is not callable"
39,766,852
<p>When I run my script:</p> <pre><code>from selenium import webdriver # from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import os import pytest import unittest from nose_parameterized import parameterized class mul...
-3
2016-09-29T09:42:53Z
39,782,866
<p>Total guess, but I think this might be your problem:</p> <pre><code>@parameterized.expand([ ("chrome"), ("firefox"), ]) </code></pre> <p>Something in <code>@parameterized</code> might not be recognizing those as tuples. Try adding a comma to make them explicitly tuples:</p> <pre><code>@parameterized.expan...
0
2016-09-30T02:44:32Z
[ "python", "selenium", "nose-parameterized" ]
how to write this querySet with Django?
39,766,855
<p>I started learning Django QuerySets but I didn't succeed to write it in this case where I must agregate 2 models related by a foreign key .</p> <p>I have 2 models <code>user</code> and <code>course</code> where course contains a foreign key of <code>user</code></p> <pre><code>class user(models.Model): first_na...
1
2016-09-29T09:43:10Z
39,766,960
<p>If what you want is a set of courses with each course instance having a set of related users you do this:</p> <pre><code>Course.objects.select_related('user').filter(course_name='science') </code></pre> <p>Please see: <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related" rel="nofoll...
3
2016-09-29T09:47:45Z
[ "python", "django", "django-models" ]
Find cells in dataframe where value is between x and y
39,766,886
<p>I want all values in a pandas dataframe as True / False depending on whether the value is between the given x and y.</p> <p>Any combining of 2 dataframes using an 'AND' operator, or any 'between' functionality from pandas would be nice. I would prefer not to loop over the columns and call the pandas.Series.between(...
3
2016-09-29T09:44:25Z
39,766,947
<p>use <code>&amp;</code> with parentheses (due to operator precedence), <code>and</code> doesn't understand how to treat an array of booleans hence the warning:</p> <pre><code>In [64]: df = pd.DataFrame([{1:1,2:2,3:6},{1:9,2:9,3:10}]) (df &gt; 2) &amp; (df &lt; 10) Out[64]: 1 2 3 0 False False T...
4
2016-09-29T09:47:03Z
[ "python", "pandas" ]
Find cells in dataframe where value is between x and y
39,766,886
<p>I want all values in a pandas dataframe as True / False depending on whether the value is between the given x and y.</p> <p>Any combining of 2 dataframes using an 'AND' operator, or any 'between' functionality from pandas would be nice. I would prefer not to loop over the columns and call the pandas.Series.between(...
3
2016-09-29T09:44:25Z
39,767,451
<p><code>between</code> is a convenient method for this. However, it is only for series objects. we can get around this by either using <code>apply</code> which operates on each row (or column) which is a series. Or, reshape the dataframe to a series with <code>stack</code></p> <p>use <code>stack</code>, <code>betw...
1
2016-09-29T10:12:05Z
[ "python", "pandas" ]
Why does it not find the variable?
39,766,919
<p>So below is my code, and I need to get the variable 'p' from the Entry widget, set it as a new variable name, the print it. For some reason, I get the following error 'NameError: name 'p' is not defined'. I have absolutely no idea how to fix it and this is my last resort. Please help me.</p> <p>Code:</p> <pre><cod...
-3
2016-09-29T09:45:39Z
39,767,059
<p>modify your code like this:</p> <pre><code>class Population(tk.Frame): def __init__(self, parent, controller): def EnterP(): b1 = p.get() print (p.get()) </code></pre>
-1
2016-09-29T09:53:00Z
[ "python", "variables", "tkinter", "nameerror" ]