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
How to ignore capitalization BUT return same capitalization as input
39,985,448
<p>My code intends to identify the first non-repeating string characters, empty strings, repeating strings (i.e. <code>abba</code> or <code>aa</code>), but it's also meant to treat lower and upper case input as the same character while returning the accurate non-repeating character in it's orignial case input. </p> <p...
1
2016-10-11T19:43:21Z
39,985,886
<p>Here's little change u can make to your code to make it work. </p> <pre><code> def first_non_repeat(string): order = [] counts = {} for x in string: char_to_look = x.lower() #### convert to lowercase for all operations if char_to_look in counts...
0
2016-10-11T20:10:27Z
[ "python", "string", "case" ]
why its printing result in reverse order?
39,985,466
<p>I am trying to understand this program :</p> <pre><code>def listSum(arr, result): if not data: return result print("print final", listSum(arr[1:], result + arr[0])) print("print A:", arr[1:]) print("print B:", result + arr[0]) listSum([1, 3, 4, 5, 6], 0) </code></pre> <p>Its printing res...
-2
2016-10-11T19:44:07Z
39,985,829
<p>Let's have a more simple example that displays the same behaviour</p> <pre><code>def rev_printer(n): if n: print(rev_printer(n-1)) return n </code></pre> <p>Then <code>rev_printer(3)</code> prints</p> <pre><code>0 1 2 3 </code></pre> <p>Why? For each <code>print</code> to finish, it has to do al...
2
2016-10-11T20:07:10Z
[ "python", "python-2.7", "python-3.x" ]
why its printing result in reverse order?
39,985,466
<p>I am trying to understand this program :</p> <pre><code>def listSum(arr, result): if not data: return result print("print final", listSum(arr[1:], result + arr[0])) print("print A:", arr[1:]) print("print B:", result + arr[0]) listSum([1, 3, 4, 5, 6], 0) </code></pre> <p>Its printing res...
-2
2016-10-11T19:44:07Z
40,049,954
<p>Sorry i seen <a href="http://stackoverflow.com/a/39815739/5904928">your message</a> too late,I just seen three question about recursion which you asked , I think you are confuse because you don't know the fundamental of recursion , How recursion works. </p> <p>For understanding recursion ---> you have to understan...
4
2016-10-14T18:35:52Z
[ "python", "python-2.7", "python-3.x" ]
Combining the Values from Multiple Keys in Dictionary Python
39,985,479
<p>In Python, I have the following dictionary of sets:</p> <pre><code>{ 1: {'Hello', 'Bye'}, 2: {'Bye', 'Do', 'Action'}, 3: {'Not', 'But', 'No'}, 4: {'No', 'Yes'} } </code></pre> <p>My goal is combine the keys which contain match values (like in this example, "Bye" and "No"), so the result will look l...
0
2016-10-11T19:45:02Z
39,985,637
<p>If there is no overlapping matches:</p> <pre><code>a = {1: {'Hello', 'Bye'}, 2: {'Bye', 'Do', 'Action'}, 3: {'Not', 'But', 'No'}, 4: {'No', 'Yes'}} output = {} for k, v in a.items(): if output: for k_o, v_o in output.items(): if v_o.intersection(v): output[k_o].update(v) ...
1
2016-10-11T19:55:43Z
[ "python", "dictionary" ]
Combining the Values from Multiple Keys in Dictionary Python
39,985,479
<p>In Python, I have the following dictionary of sets:</p> <pre><code>{ 1: {'Hello', 'Bye'}, 2: {'Bye', 'Do', 'Action'}, 3: {'Not', 'But', 'No'}, 4: {'No', 'Yes'} } </code></pre> <p>My goal is combine the keys which contain match values (like in this example, "Bye" and "No"), so the result will look l...
0
2016-10-11T19:45:02Z
39,985,668
<p>If there are overlapping matches and you want the longest matches:</p> <pre><code>from collections import defaultdict d = { 1: {'Hello', 'Bye'}, 2: {'Bye', 'Do', 'Action'}, 3: {'Not', 'But', 'No'}, 4: {'No', 'Yes'} } grp = defaultdict(list) # first group all keys with common words for k, v in d.it...
1
2016-10-11T19:57:46Z
[ "python", "dictionary" ]
for loop, trying to exclude numbers in the if and else statement
39,985,522
<p>I am reletively new to python, as you can see if the 'n' is divisible by 5, 6 and 5&amp;6 something happens but for those numbers it still shows (ex. 100O) when it is divisble by 5 or 6 i dont want the 'n' number to print. Any suggestions will help but please keep it at a novice level so i may learn. </p> <pre><cod...
0
2016-10-11T19:48:17Z
39,985,640
<pre><code>def main(): numHigh = 101 for n in range(numHigh, 0, -1): if (n % 5 == 0): print("Where do you see yourself in five years?") elif (n % 6 == 0): print("I'll believe six impossible things before breakfast.") elif (n % 5 == 0) &amp; (numHigh % 6 == 0): print("Thirty days in h...
1
2016-10-11T19:56:01Z
[ "python" ]
for loop, trying to exclude numbers in the if and else statement
39,985,522
<p>I am reletively new to python, as you can see if the 'n' is divisible by 5, 6 and 5&amp;6 something happens but for those numbers it still shows (ex. 100O) when it is divisble by 5 or 6 i dont want the 'n' number to print. Any suggestions will help but please keep it at a novice level so i may learn. </p> <pre><cod...
0
2016-10-11T19:48:17Z
39,985,650
<p>The print(n) is in the beginning of your for loop so it will print n every time the loop runs. Instead you should create an else statement after your ifs and elifs. That way if all those ifs/elifs aren't true it will print n. </p> <p>Like this</p> <pre><code>if … elif … elif … else: print(n) </code></pre...
1
2016-10-11T19:56:40Z
[ "python" ]
Current options for Django permissions CBV/DRF
39,985,652
<p>What are the currently available options for permissions in Django that work for both class-based-views and Django-REST-Framework?</p> <p>I don't want object-level permissions but rather something like <a href="https://github.com/dfunckt/django-rules" rel="nofollow">rules</a>, <a href="https://github.com/maraujop/d...
0
2016-10-11T19:56:45Z
40,087,591
<p>Actually, <code>django-rules</code> already integrates well into the permission system of Django. Thus, <code>User.has_perm()</code> works out of the box with it.</p>
0
2016-10-17T13:23:12Z
[ "python", "django", "django-rest-framework" ]
onclick turtle method in python 3
39,985,755
<p>I am re-creating the game of x and os, but I can't seem to get the onclick method in python3 to work here's my code:</p> <pre><code>def hide(t): t.hideturtle() def begin(): global playersTurn if playersTurn == 0: playerOnesTurn.showturtle() playerOnesTurn.onclick(hide) else: ...
0
2016-10-11T20:02:29Z
39,986,739
<p>The <code>onclick()</code> handler expects a function that takes the x &amp; y positions as arguments. So, instead do something like:</p> <pre><code>playerOnesTurn.onclick(lambda x, y: playerOnesTurn.hideturtle()) </code></pre> <p>Other comments: if you're only checking <code>playersTurn</code>, not changing it, ...
0
2016-10-11T21:07:29Z
[ "python", "python-3.x", "turtle-graphics" ]
web-scrapping hidden href using python
39,985,772
<p>I´m using python to get all the possible href from the following webpage: </p> <p><a href="http://www.congresovisible.org/proyectos-de-ley/" rel="nofollow">http://www.congresovisible.org/proyectos-de-ley/</a></p> <p>example these two</p> <pre><code>href="ppor-medio-de-la-cual-se-dictan-medidas-para-defender-el-a...
0
2016-10-11T20:03:32Z
39,986,592
<blockquote> <p>Prenote: I assume you use Python 3+.</p> </blockquote> <p>What happens is, you click "See All", it requests an API, takes data, dumps into view. This is all AJAX process.</p> <p>The hard and complicated way is to use, Selenium, but there is no need actually. With a little bit debug on browser, you c...
1
2016-10-11T20:57:07Z
[ "javascript", "python", "web-scraping", "href" ]
Custom 404 django template
39,985,774
<p>I'm trying to customize the 404 error pages in my application. After searching many possible solutions, I created an 404.html template, added a method which should handle HTTP Error 404 and edited my urls.py.</p> <p>But I guess I'm doing something really wrong. My log presents an invalid syntax error and I cannot s...
0
2016-10-11T20:03:37Z
39,985,871
<p>The <code>handler404</code> should be outside <code>urlpatterns</code>. If the view is called <code>page_not_found</code>, then it should refer to <code>page_not_found</code>, not <code>handler404</code>.</p> <pre><code>handler404 = 'views.page_not_found' urlpatterns = [ url(r'^$', views.home), ] </code></pre>...
1
2016-10-11T20:09:46Z
[ "python", "django" ]
How to use gluLookAt in PyOpenGL?
39,985,804
<p>I'm trying to learn PyOpenGL, but I'm not sure how to use gluLookAt to move the camera. I've got an image displaying, but I think I might be missing something that allows me to use gluLookAt? Incoming wall o'text, I'm not sure where the problem might be. I've cut out the shaders and the texture code, because I don't...
1
2016-10-11T20:05:57Z
39,986,290
<p>The GLU library is for use with the fixed-function pipeline. It doesn't work with modern OpenGL, when you're using vertex shaders (at least, not unless you're doing compatibility-profile stuff, but it looks like you're not doing that). Instead, you will create the equivalent matrix, and use it as part of one of yo...
2
2016-10-11T20:35:37Z
[ "python", "pyopengl", "glu", "glulookat" ]
pandas merge on columns with different names and avoid duplicates
39,985,861
<p>How can I merge two pandas DataFrames on two columns with different names and keep one of the columns?</p> <pre><code>df1 = pd.DataFrame({'UserName': [1,2,3], 'Col1':['a','b','c']}) df2 = pd.DataFrame({'UserID': [1,2,3], 'Col2':['d','e','f']}) pd.merge(df1, df2, left_on='UserName', right_on='UserID') </code></pre> ...
1
2016-10-11T20:09:21Z
39,985,966
<p>There is nothing really nice in it: it's meant to be keeping the columns as the larger cases like left right or outer joins would bring additional information with two columns. Don't try to overengineer your merge line, be explicit as you suggest</p> <p>Solution 1:</p> <pre><code>df2.columns = ['Col2', 'UserName']...
2
2016-10-11T20:15:38Z
[ "python", "pandas", "merge" ]
pandas merge on columns with different names and avoid duplicates
39,985,861
<p>How can I merge two pandas DataFrames on two columns with different names and keep one of the columns?</p> <pre><code>df1 = pd.DataFrame({'UserName': [1,2,3], 'Col1':['a','b','c']}) df2 = pd.DataFrame({'UserID': [1,2,3], 'Col2':['d','e','f']}) pd.merge(df1, df2, left_on='UserName', right_on='UserID') </code></pre> ...
1
2016-10-11T20:09:21Z
39,985,970
<p>How about set the <code>UserID</code> as index and then join on index for the second data frame?</p> <pre><code>pd.merge(df1, df2.set_index('UserID'), left_on='UserName', right_index=True) # Col1 UserName Col2 # 0 a 1 d # 1 b 2 e # 2 c 3 f </code></p...
2
2016-10-11T20:15:50Z
[ "python", "pandas", "merge" ]
Python: POST request not working?
39,986,019
<p>Making a simple POST request to Firebase. For some reason, it's not working. cURL with the same data is working, no issues. Any ideas?</p> <p>Code below:</p> <pre><code>import requests r = requests.post("https://testapp-f55e1.firebaseio.com/test.json", data={"location":{"altitude":"200","latitude":"23.2", "lon...
0
2016-10-11T20:19:47Z
39,986,195
<p>It expects <em>json</em> so replace <em>data=</em> with <em>json=</em>, requests will call <em>json.dumps</em> and set the headers for you:</p> <pre><code>In [6]: import requests ...: r = requests.post("https://testapp-f55e1.firebaseio.com/test.json", json ...: ={"location":{"altitude":"200","latitude":"23.2"...
2
2016-10-11T20:30:21Z
[ "python", "curl", "firebase", "python-requests" ]
Django template {%url%} concatenates to existing url
39,986,025
<p>Problem accured after moving application to other server.</p> <p>For example url: <a href="http://example.com/path/otherpath" rel="nofollow">http://example.com/path/otherpath</a>. And I want logout: </p> <pre><code>&lt;a href="{% url 'logout' %}"&gt;Logout&lt;/a&gt; </code></pre> <p>it goes to: <a href="http://ex...
0
2016-10-11T20:20:06Z
39,986,333
<p>Problem was in fastcgi_params file. Works with this settings:</p> <pre><code> fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param ...
0
2016-10-11T20:38:49Z
[ "python", "nginx", "django-templates", "django-urls", "django-1.6" ]
Converting days since epoch to date
39,986,041
<p>How can one convert a serial date number, representing the number of days since epoch (1970), to the corresponding date string? I have seen multiple posts showing how to go from string to date number, but I haven't been able to find any posts on how to do the reverse.</p> <p>For example, <code>15951</code> correspo...
0
2016-10-11T20:21:01Z
39,988,256
<p>Use the <code>datetime</code> package as follows:</p> <pre><code>import datetime def serial_date_to_string(srl_no): new_date = datetime.datetime(1970,1,1,0,0) + datetime.timedelta(srl_no - 1) return new_date.strftime("%Y-%m-%d") </code></pre> <p>This is a function which returns the string as required.</p> ...
1
2016-10-11T23:22:23Z
[ "python", "date", "datetime", "epoch" ]
Python Pandas dataframe division error: operation not ' 'safe' '
39,986,053
<p>I am trying to normalize some columns of a Pandas DataFrame in Python to their sum. I have the following the DataFrame:</p> <pre><code>import pandas as pd l_a_2015 = ['Farh','Rob_Sens','Pressure','Septic',10.0,45.,52.,72.51] l_a_2010 = ['Water_Column','Log','Humid','Top_Tank',58.64,35.42,10.,30.] df = pd.DataFrame...
1
2016-10-11T20:21:36Z
39,986,199
<p>try this:</p> <pre><code>In [5]: df Out[5]: Output_A Tonnes_Rem Log_Act_All Readout A1 A2 A3 A4 0 Water_Column Log Humid Top_Tank 58.64 35.42 10.0 30.00 1 Farh Rob_Sens Pressure Septic 10.00 45.00 52.0 72.51 In [8]: cols = df.select_dtypes(include=['n...
2
2016-10-11T20:30:41Z
[ "python", "pandas", "dataframe", "divide" ]
how does .isdigit() work in this case?
39,986,198
<p>When I was looking for a solution for the problem "count digits in a given string containing both letters and digits" there was one with built-in function .isdigit(). Here it is:</p> <pre><code>def count_numbers1(a): return sum(int(x) for x in a if x.isdigit()) </code></pre> <p>It works nicely but I cannot get...
-1
2016-10-11T20:30:34Z
39,986,280
<p>First of all, the function doesn't <em>count</em> digits in a string. It <em>sums up</em> the digits in a string. Secondly, <code>str.isdigit()</code> only returns true if <strong>all</strong> characters in a string are digits, not just one of the characters. From the <a href="https://docs.python.org/3/library/stdty...
6
2016-10-11T20:34:58Z
[ "python", "string", "sum", "digits" ]
Create a query with Django
39,986,205
<p>Hi everyone I and try to do a query with the params pass by URL in my case the uRL is like</p> <pre><code>http://127.0.0.1:8000/api/cpuProjects/cpp/es http://127.0.0.1:8000/api/cpuProjects/cpp,ad/es </code></pre> <p>My code to create the query is like this </p> <pre><code>def findElem(request, **kwargs): projec...
0
2016-10-11T20:31:11Z
39,986,352
<p>Im sorry to say that, but passing your variables directly into a query is dangerous in every language. Try something more like this. Django will take care for you to escape your arguments proper, otherwise you get SQL injection possibilities:</p> <pre><code>from foo.models import CPUSModel projects_name = ... what...
2
2016-10-11T20:39:50Z
[ "python", "django" ]
Create a query with Django
39,986,205
<p>Hi everyone I and try to do a query with the params pass by URL in my case the uRL is like</p> <pre><code>http://127.0.0.1:8000/api/cpuProjects/cpp/es http://127.0.0.1:8000/api/cpuProjects/cpp,ad/es </code></pre> <p>My code to create the query is like this </p> <pre><code>def findElem(request, **kwargs): projec...
0
2016-10-11T20:31:11Z
39,986,527
<p>The best thing to do is to use Django's ORM API to make queries:</p> <pre><code>from foo.models import ProjCpu ... projects_name = ... ... ProjCpu.objects.filter(project__in=projects_name) </code></pre> <p>You can read everything about it in the Django documentation.</p> <p>Basically That's all you need to know, ...
1
2016-10-11T20:52:54Z
[ "python", "django" ]
Django: django.test TestCase self.assertTemplateUsed
39,986,243
<p>Working on <a href="http://hellowebapp.com" rel="nofollow">Hello Web App</a>.</p> <p>Please help with TestCase: test_edit_thing.</p> <p>Here's the error details:</p> <p>The error in case of '/things/django-book/edit/':</p> <pre><code># AssertionError: No templates used to render the response response = self.clie...
0
2016-10-11T20:32:43Z
39,986,769
<p>So the problem that you was having is that your user wasn't authenticated, and if user is not the same as user of the thing you raise Http404</p> <p>It in your <code>edit_thing</code> view</p> <pre><code>if thing.user != request.user: raise Http404 </code></pre> <p>So you needed to be authenticated. And that ...
0
2016-10-11T21:09:03Z
[ "python", "django", "python-2.7", "django-templates", "django-testing" ]
POSTing and GETing with grequests
39,986,254
<p>I'm using grequests to scape websites faster. However, I also need to login to the website. </p> <p>Before (just using requests) I could do: </p> <p>where <code>headers</code> is my <code>User-Agent</code>. </p> <pre><code>with requests.Session() as s: s.headers.update(headers) s.post(loginURL, files = d...
1
2016-10-11T20:33:13Z
39,986,308
<p>First login the session, then pass it explicitly to your grequest like this:</p> <pre><code>requests = [] for url in urls: request = grequests.AsyncRequest( method='GET', url=url, session=session, ) requests.append(request) </code></pre>
2
2016-10-11T20:37:09Z
[ "python", "python-3.x", "python-requests", "grequests" ]
POSTing and GETing with grequests
39,986,254
<p>I'm using grequests to scape websites faster. However, I also need to login to the website. </p> <p>Before (just using requests) I could do: </p> <p>where <code>headers</code> is my <code>User-Agent</code>. </p> <pre><code>with requests.Session() as s: s.headers.update(headers) s.post(loginURL, files = d...
1
2016-10-11T20:33:13Z
39,986,310
<p>You can pass in the <em>Session</em> object exactly the same as the <em>headers</em>:</p> <pre><code>with requests.Session() as s: s.headers.update(headers) s.post(loginURL, files = data) s.get(scrapeURL) rs = (grequests.get(u, headers=header, session=s) for u in urls) response = grequests.ma...
2
2016-10-11T20:37:19Z
[ "python", "python-3.x", "python-requests", "grequests" ]
Serialize Haystack SearchQuerySet
39,986,317
<p>I have some Django queries dumped in files that are delayed so I pass as parameter <code>sql_with_params</code> to later execute in the delayed a <code>raw</code> query.</p> <p>I have migrated all queries to haystack so I wan't to do the same with <code>SearchQuerySet</code>.</p> <p>Is there any way to get the raw...
0
2016-10-11T20:37:53Z
39,986,564
<p>Sure, here's one way that unfortunately requires a bit of plumbing. You can create a custom search engine and set its query to your own query definition inheriting from <code>ElasticsearchSearchQuery</code>:</p> <pre><code>from haystack.backends.elasticsearch_backend import ElasticsearchSearchEngine, ElasticsearchS...
0
2016-10-11T20:54:58Z
[ "python", "django", "elasticsearch", "django-haystack" ]
How do I open a tab delimited text file in pandas so that I can then use it for exploratory data analysis?
39,986,386
<p>I have a tab delimited file with data about some movies. Some movie titles are enclosed in a double quote. How can I read the file into a pandas dataframe and how can I remove the double quote from the movie titles? </p> <p>I know how to do it in R and I know how to remove the double quotes. However, is there an e...
0
2016-10-11T20:42:29Z
39,986,488
<p>First you'll want to import pandas</p> <pre><code>Df = pandas.read_csv("file.csv") </code></pre> <p>Get rid of double quotes with</p> <pre><code>Df2 = Df['columnwithquotes'].apply(lambda x: x.replace('"', '')) </code></pre>
0
2016-10-11T20:50:27Z
[ "python", "pandas" ]
How do I open a tab delimited text file in pandas so that I can then use it for exploratory data analysis?
39,986,386
<p>I have a tab delimited file with data about some movies. Some movie titles are enclosed in a double quote. How can I read the file into a pandas dataframe and how can I remove the double quote from the movie titles? </p> <p>I know how to do it in R and I know how to remove the double quotes. However, is there an e...
0
2016-10-11T20:42:29Z
39,986,823
<p>You can use <code>read_table</code> as its <code>quotechar</code> parameter is set to <code>'"'</code> by default and will so remove the double quotes.</p> <pre><code>import pandas as pd from io import StringIO the_data = """ A B C D ABC 2016-6-9 0:00 95 "foo foo" ABC 2016-6-10 0:00 0 "bar bar" """ df ...
0
2016-10-11T21:12:36Z
[ "python", "pandas" ]
How do I open a tab delimited text file in pandas so that I can then use it for exploratory data analysis?
39,986,386
<p>I have a tab delimited file with data about some movies. Some movie titles are enclosed in a double quote. How can I read the file into a pandas dataframe and how can I remove the double quote from the movie titles? </p> <p>I know how to do it in R and I know how to remove the double quotes. However, is there an e...
0
2016-10-11T20:42:29Z
39,987,002
<p>First you can read tab delimited files using either <code>read_table</code> or <code>read_csv</code>. The former uses tab delimiter by default, for the latter you need to specify it:</p> <pre><code>import pandas as pd df = pd.read_csv('yourfile.txt', sep='\t') </code></pre> <p>Or:</p> <pre><code>import pandas as ...
0
2016-10-11T21:25:06Z
[ "python", "pandas" ]
Typical coin change program in python that asks for specific amounts of each coin
39,986,520
<p>Given a number "x" and a sorted array of coins "coinset", write a function that returns the amounts for each coin in the coinset that sums up to X or indicate an error if there is no way to make change for that x with the given coinset. For example, with x=7 and a coinset of [1,5,10,25]a valid answer would be {1: 7}...
-1
2016-10-11T20:52:45Z
39,986,802
<p>As a concept, change <strong>coins_so_far</strong> to <strong>coins_this_call</strong>.</p> <p>Your recursion steps change to something of this ilk; although it's not complete, I hope you see the idea.</p> <pre><code>for c in change(n-sum(coins_this_call), coins_available[:]): yield coins_this_call.append(c) <...
0
2016-10-11T21:11:13Z
[ "python", "algorithm", "python-2.7", "data-structures" ]
Which Python version used in Django project? 2 or 3?
39,986,615
<p>When I open someone's Django project, I need a time for understanding which Python version is used here. I try to find print or print() methods, but some Django projects contain both print methods. How I can at once know, which version of Python is used in the Django project? </p>
-2
2016-10-11T20:59:26Z
39,986,799
<p>depends on which version you've installed. but really, that's all in the Django-docu.. <a href="https://docs.djangoproject.com/en/1.8/intro/install/" rel="nofollow">here you go! </a>;) try to check it before you ask that kind of question.</p>
-2
2016-10-11T21:11:07Z
[ "python", "django", "version" ]
Which Python version used in Django project? 2 or 3?
39,986,615
<p>When I open someone's Django project, I need a time for understanding which Python version is used here. I try to find print or print() methods, but some Django projects contain both print methods. How I can at once know, which version of Python is used in the Django project? </p>
-2
2016-10-11T20:59:26Z
39,986,982
<p>This is a list of the syntax that isn't backwards compatible with python 2. Use it to determine their version.</p> <p><a href="https://docs.python.org/3/whatsnew/3.0.html" rel="nofollow">What’s New In Python 3.0</a></p>
0
2016-10-11T21:23:44Z
[ "python", "django", "version" ]
what is the required order for S3 element values when making a Post request?
39,986,653
<p>I'm trying to upload a file to S3 by doing :</p> <pre><code>r_response = requests.post(presigned_post["url"], json=presigned_post["fields"], files=files) </code></pre> <p>but I'm getting the following error:</p> <blockquote> <p>Bucket POST must contain a field named 'key'. If it is specified, please check the ...
0
2016-10-11T21:01:50Z
39,988,770
<p>I was originally doing:</p> <pre><code>r_response = requests.post(presigned_post["url"], json=presigned_post["fields"], files=files) </code></pre> <p>I changed the <code>json</code> to <code>data</code> and it worked:</p> <pre><code>r_response = requests.post(presigned_post["url"], data=presigned_post["fields"], ...
0
2016-10-12T00:32:54Z
[ "python", "amazon-s3", "boto3" ]
f(x).subs() substitution in sympy (python)
39,986,674
<p>I defined symbols a and f. I'm expecting to use "a(3).subs(a,f)" to get f(3), but instead I got a(3). What's wrong with it?</p> <pre><code>a, f = symbols('a f') a(3).subs(a,f) </code></pre>
0
2016-10-11T21:02:48Z
39,986,773
<p>You've defined <code>f</code> as a function and then you replaced it with the return value from <code>symbols()</code>.</p>
1
2016-10-11T21:09:07Z
[ "python", "sympy" ]
f(x).subs() substitution in sympy (python)
39,986,674
<p>I defined symbols a and f. I'm expecting to use "a(3).subs(a,f)" to get f(3), but instead I got a(3). What's wrong with it?</p> <pre><code>a, f = symbols('a f') a(3).subs(a,f) </code></pre>
0
2016-10-11T21:02:48Z
39,993,374
<p>You can use <code>replace</code> to change the function. Here are some examples. </p> <pre><code>import sympy as sp f = sp.Function('f') g = sp.Function('g') x,y = sp.symbols('x, y') f(x).replace(f, g) </code></pre> <blockquote> <p><code>g(x)</code></p> </blockquote> <pre><code>f(x).replace(f, sp.sin) </code>...
0
2016-10-12T07:56:28Z
[ "python", "sympy" ]
Need Help for Quadratic formula on python
39,986,707
<p>I just started learning Python in school, here is my code for the quadratic formula solver. Problem is on line 4.</p> <pre><code>a=int(input('a= ')) # A-stvis mnishvnelobis micema b=int(input('b= ')) # B-stvis mnishvnelobis micema c=int(input('c= ')) # C-stvis mnishvenlobis micema int(a)*(x2)+int(b)*x+c=0 d=(-b2)-4...
0
2016-10-11T21:05:03Z
39,986,789
<pre><code>from math import sqrt a = int(input('a= ')) # A-stvis mnishvnelobis micema b = int(input('b= ')) # B-stvis mnishvnelobis micema c = int(input('c= ')) # C-stvis mnishvenlobis micema d = b**2 - 4*a*c x1 = (-b - sqrt(d))/2 x2 = (-b + sqrt(d))/2 print("x1 =", x1) print("x2 =", x2) </code></pre> <p>Your equati...
1
2016-10-11T21:10:06Z
[ "python", "math", "formula", "quadratic" ]
Search Specific Keyword From a File and add description associated to it to different file with Python
39,986,781
<p>Below text file shows the Description of Channel Name &amp; the Channel Event</p> <p><strong><em>desc.txt file:</em></strong></p> <pre><code>Channel Name: CBS Event Name: FIFA World Cup 2018 Qualifying Channel Name: BEINSPORTS Event Name: NFL </code></pre> <p>Below Python code only looks for the First "Event Na...
0
2016-10-11T21:09:36Z
39,986,896
<p>Notice that you're opening the file in write (<code>'w'</code>) mode so the entire content of the file test_live.txt is wiped with every iteration. Use append (<code>'a'</code>) mode instead.</p>
0
2016-10-11T21:18:13Z
[ "python", "file", "python-3.x" ]
Search Specific Keyword From a File and add description associated to it to different file with Python
39,986,781
<p>Below text file shows the Description of Channel Name &amp; the Channel Event</p> <p><strong><em>desc.txt file:</em></strong></p> <pre><code>Channel Name: CBS Event Name: FIFA World Cup 2018 Qualifying Channel Name: BEINSPORTS Event Name: NFL </code></pre> <p>Below Python code only looks for the First "Event Na...
0
2016-10-11T21:09:36Z
39,986,898
<p>You keep opening the same file and writing one line to it. You have two options: You can either open it once outside the loop (more efficient), and close it when exiting the loop (you should close your other <code>open</code> statement too). Or you can open it with <code>'a'</code> instead of <code>'w'</code> to <em...
1
2016-10-11T21:18:17Z
[ "python", "file", "python-3.x" ]
Search Specific Keyword From a File and add description associated to it to different file with Python
39,986,781
<p>Below text file shows the Description of Channel Name &amp; the Channel Event</p> <p><strong><em>desc.txt file:</em></strong></p> <pre><code>Channel Name: CBS Event Name: FIFA World Cup 2018 Qualifying Channel Name: BEINSPORTS Event Name: NFL </code></pre> <p>Below Python code only looks for the First "Event Na...
0
2016-10-11T21:09:36Z
39,986,998
<p>What the previous posts indicated with the implemented code.</p> <pre><code>flist = open('/tmp/desc.txt', 'r').readlines() file2 = open('/tmp/test_live.txt','a') for line in flist: if line.startswith("Event Name:"): eventname = line[12:-1] file2.write(eventname + "\n") #Close O...
0
2016-10-11T21:24:48Z
[ "python", "file", "python-3.x" ]
How to limit the size of pandas queries on HDF5 so it doesn't go over RAM limit?
39,986,786
<p>Let's say I have a pandas Dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame() df Column1 Column2 0 0.189086 -0.093137 1 0.621479 1.551653 2 1.631438 -1.635403 3 0.473935 1.941249 4 1.904851 -0.195161 5 0.236945 -0.288274 6 -0.473348 0.403882 7 0.953940 1.718043 8 -0.289416 0.790983...
6
2016-10-11T21:10:02Z
39,986,894
<p>Here is a small demonstration of how to use the <code>chunksize</code> parameter when calling <code>HDFStore.select()</code>:</p> <pre><code>for chunk in store.select('df', columns=['column1', 'column2'], where='column1==5', chunksize=10**6): # process `chunk` DF </code></pre>
3
2016-10-11T21:17:59Z
[ "python", "pandas", "dataframe", "hdf5", "pytables" ]
How to check, whether exception was raisen in the current scope?
39,986,820
<p>I use the following code to call an arbitrary callable <code>f()</code> with appropriate number of parameters:</p> <pre><code>try: res = f(arg1) except TypeError: res = f(arg1, arg2) </code></pre> <p>If <code>f()</code> is a two parameter function, calling it with just one parameter raises <code>TypeError<...
0
2016-10-11T21:12:09Z
40,005,349
<p>You can capture the exception object and examine it.</p> <pre><code>try: res = f(arg1) except TypeError as e: if "f() missing 1 required positional argument" in e.args[0]: res = f(arg1, arg2) else: raise </code></pre> <p>Frankly, though, not going the extra length to classify the excep...
0
2016-10-12T17:59:42Z
[ "python", "python-2.7", "python-3.x", "debugging", "exception-handling" ]
How to check, whether exception was raisen in the current scope?
39,986,820
<p>I use the following code to call an arbitrary callable <code>f()</code> with appropriate number of parameters:</p> <pre><code>try: res = f(arg1) except TypeError: res = f(arg1, arg2) </code></pre> <p>If <code>f()</code> is a two parameter function, calling it with just one parameter raises <code>TypeError<...
0
2016-10-11T21:12:09Z
40,044,648
<p>Finally figured it out:</p> <pre><code>def exceptionRaisedNotInTheTryBlockScope(): return sys.exc_info()[2].tb_next is not None </code></pre> <p><code>sys.exc_info()</code> returns a 3-element <code>tuple</code>. Its last element is the traceback of the last exception. If the traceback object is the only one i...
0
2016-10-14T13:40:11Z
[ "python", "python-2.7", "python-3.x", "debugging", "exception-handling" ]
Is there a way to check if a string is a valid filter for a django queryset?
39,986,829
<p>I'm trying to add some functionality to give a user the ability to filter a paginated queryset in Django via URL get parameters, and have got this successfully working:</p> <pre><code>for f in self.request.GET.getlist('f'): try: k,v = f.split(':', 1) queryset = queryset.filter(**{k:v}) excep...
0
2016-10-11T21:13:07Z
39,990,884
<p>The short answer is no, but there are other options.</p> <p>Django does not provide, nor make it easy to create, the kind of validation function you're asking about. There are not just fields and forward relationships that you can filter on, but also reverse relationships, for which a <code>related_name</code> or ...
0
2016-10-12T05:06:50Z
[ "python", "django", "django-queryset", "django-orm" ]
Is there a way to check if a string is a valid filter for a django queryset?
39,986,829
<p>I'm trying to add some functionality to give a user the ability to filter a paginated queryset in Django via URL get parameters, and have got this successfully working:</p> <pre><code>for f in self.request.GET.getlist('f'): try: k,v = f.split(':', 1) queryset = queryset.filter(**{k:v}) excep...
0
2016-10-11T21:13:07Z
40,004,003
<p>You can start by looking at the field names:</p> <pre><code>qs.model._meta.get_all_field_names() </code></pre> <p>You are also probably going to want to work with the extensions such as <code>field__icontains</code>, <code>field__gte</code> etc. So more work will be required. </p> <p><em>Disclaimer</em>: <code...
1
2016-10-12T16:44:35Z
[ "python", "django", "django-queryset", "django-orm" ]
python exceptions with same name but different subclassing
39,986,849
<p>I am reading the <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">python doc</a> and it mentions that </p> <blockquote> <p>Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.</p> </blockquote> <p>I'm not sure why it is possib...
0
2016-10-11T21:14:39Z
39,986,955
<p>Exceptions are just specific types of classes. Class names are simply what they are defined as. Forbidding classes to have the same name would brake lots of coding schemes. One such example actually works on exceptions: programs that need to be backwards compatible with python2.6 will often override <code>subprocess...
1
2016-10-11T21:21:55Z
[ "python", "exception" ]
spark dataframe read text file without headers
39,986,893
<p>i have a text file with no headers, how can i read it using spark dataframe api and specify headers. Is there a way to specify my schema</p> <p>sample_data = spark.read.option("header", "false").text(sample)</p> <p>print "Data size is {}".format(sample_data.count())</p> <p>print type(sample_data)</p> <p>print sa...
-2
2016-10-11T21:17:56Z
39,987,744
<p>First, save your file as csv. You can specify the schema:</p> <pre><code>schema = StructType([ \ StructField("column1", StringType(), True), \ StructField("column2", DoubleType(), True), \ StructField("column3", IntegerType(), True)]) </code></pre> <p>And so on. If you're using spark 2.0 +:</p> <pre><...
0
2016-10-11T22:26:40Z
[ "python", "apache-spark", "dataframe", "pyspark" ]
Making a box in python with controlled inputs from user
39,986,902
<p>I am trying to make a box where the user inputs the width, height, what kind of symbol the box should be made out of and the fill(inside the box). I am a new python coder, so any suggestions would be great, but the more novice level responses the better so i may learn and not skip into far advance techniques.</p> <...
-1
2016-10-11T21:18:38Z
39,987,042
<p>Use <code>input("Enter number")</code> to get input from the user. You should first loop on height then on width. To print with no new-line use <code>end=""</code> as a parameter to <code>print</code>. You used <code>i</code> instead of <code>b</code> and <code>a</code>. That's about it I think. Next time ask more s...
0
2016-10-11T21:27:50Z
[ "python" ]
Making a box in python with controlled inputs from user
39,986,902
<p>I am trying to make a box where the user inputs the width, height, what kind of symbol the box should be made out of and the fill(inside the box). I am a new python coder, so any suggestions would be great, but the more novice level responses the better so i may learn and not skip into far advance techniques.</p> <...
-1
2016-10-11T21:18:38Z
39,987,107
<pre><code>def main(): # input is your friend here width = input("Please enter the width of the box: ") #width = print(int("Please enter the width of the box: ")) # input etc.. height = print(int("Please enter the height of the box: ")) symbol = print("Please enter the symbol for the box outl...
2
2016-10-11T21:32:41Z
[ "python" ]
Making a box in python with controlled inputs from user
39,986,902
<p>I am trying to make a box where the user inputs the width, height, what kind of symbol the box should be made out of and the fill(inside the box). I am a new python coder, so any suggestions would be great, but the more novice level responses the better so i may learn and not skip into far advance techniques.</p> <...
-1
2016-10-11T21:18:38Z
39,987,997
<pre><code>def main(): width = int(input("Please enter the width of the box: ")) height = int(input("Please enter the height of the box: ")) symbol = input("Please enter the symbol for the box outline: ") fill = input("Please enter the symbol for the box fill: ") dictionary = [] for row in range...
0
2016-10-11T22:53:02Z
[ "python" ]
Invalid Syntax error python 3.5.2
39,986,911
<p>I'm getting syntax error in this particular line.</p> <pre><code>print "Sense %i:" %(i), </code></pre> <p><strong>Full code:</strong></p> <pre><code>for i in range(len(meas)): p = sense(p, meas[i]) r = [format(j,'.3f') for j in p] print "Sense %i:" % (i), print r, entropy(p) p = move(p, mo...
0
2016-10-11T21:19:14Z
39,987,024
<p>Try this:</p> <pre><code>print ("Sense %s:" %i) </code></pre> <p>Will work just fine</p>
0
2016-10-11T21:26:16Z
[ "python", "python-3.x", "syntax" ]
Invalid Syntax error python 3.5.2
39,986,911
<p>I'm getting syntax error in this particular line.</p> <pre><code>print "Sense %i:" %(i), </code></pre> <p><strong>Full code:</strong></p> <pre><code>for i in range(len(meas)): p = sense(p, meas[i]) r = [format(j,'.3f') for j in p] print "Sense %i:" % (i), print r, entropy(p) p = move(p, mo...
0
2016-10-11T21:19:14Z
39,987,030
<p>In python 3, print is a function, you have to use brackets: <code>print("Sense %i:" %(i))</code></p>
0
2016-10-11T21:26:40Z
[ "python", "python-3.x", "syntax" ]
Invalid Syntax error python 3.5.2
39,986,911
<p>I'm getting syntax error in this particular line.</p> <pre><code>print "Sense %i:" %(i), </code></pre> <p><strong>Full code:</strong></p> <pre><code>for i in range(len(meas)): p = sense(p, meas[i]) r = [format(j,'.3f') for j in p] print "Sense %i:" % (i), print r, entropy(p) p = move(p, mo...
0
2016-10-11T21:19:14Z
39,987,093
<p>Several things:</p> <ul> <li>In Python 3, <code>print</code> is a function, no more a statement like it was with Python 2. So, you need to add parenthesis to call the function,</li> <li>the <code>%</code> operator used for string formatting is deprecated. With Python 3, you should use the <code>format</code> method...
1
2016-10-11T21:31:25Z
[ "python", "python-3.x", "syntax" ]
Pandas Multiple columns same name
39,986,925
<p>I am creating a <code>dataframe</code> from <code>csv</code>.I have gone thru the docs,multiple <code>SO</code> posts,links as i have just started <code>Pandas</code> but didnt get it.The csv has multiple columns with same names say <code>a</code>.</p> <p>So after forming <code>dataframe</code> and when i do <code>...
4
2016-10-11T21:19:43Z
39,986,959
<p>the relevant parameter is <code>mangle_dupe_cols</code></p> <p>from the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">docs</a></p> <blockquote> <pre><code>mangle_dupe_cols : boolean, default True Duplicate columns will be specified as 'X.0'...'X.N', rather ...
5
2016-10-11T21:22:15Z
[ "python", "python-2.7", "csv", "pandas" ]
Variables reset with every recursive call so function doesn't work. (Python)
39,986,949
<p>Code: </p> counter and storage are reset every time the function is called recusively <pre><code>def bin_to_dec(b): '''Takes a string b that represents a binary number and uses recursion to convert the number from binary to decimal.''' counter = -1 storage = 0 if b == 0: ...
-1
2016-10-11T21:21:40Z
39,987,215
<p>Anything you want to be preserved through function calls should not be local to the function. There are many ways to preserve values between calls. The recommended way in your case is to pass it as a parameter to the function.</p>
0
2016-10-11T21:40:44Z
[ "python" ]
How to distribute Python libraries to users without internet
39,986,952
<p>Package managers like conda, pip and their online repositories make distributing packages easy and robust. But I am looking for ways to distribute to users that want to install and run my library on machines that are deliberately disconnected from internet for security purposes.</p> <p>I am to assume these computer...
0
2016-10-11T21:21:47Z
39,987,141
<p>There are many options:</p> <ol> <li>Create a pip repository in the offline network.</li> <li>Deploy your project with its dependencies. Use setuptools to create a <code>setup.py</code> file for easy installation.</li> <li>Use py2exe to create an executable instead of a python program.</li> </ol>
0
2016-10-11T21:34:51Z
[ "python", "anaconda", "software-distribution" ]
How to distribute Python libraries to users without internet
39,986,952
<p>Package managers like conda, pip and their online repositories make distributing packages easy and robust. But I am looking for ways to distribute to users that want to install and run my library on machines that are deliberately disconnected from internet for security purposes.</p> <p>I am to assume these computer...
0
2016-10-11T21:21:47Z
39,987,208
<p>Here are the steps:</p> <ol> <li>Create a virtual environment for the project. This link will help you create virtual environments <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></li> <li>Add all the libraries that you want...
-1
2016-10-11T21:40:11Z
[ "python", "anaconda", "software-distribution" ]
Graceful interrupt of EventLoop.sock_accept()
39,986,978
<p>Consider the following code, how to stop execution in <code>listen()</code>? it seems to hang after <code>sock.close()</code> being called. No exceptions are raised</p> <pre><code>#!/usr/bin/env python3.5 import asyncio, socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8080)...
0
2016-10-11T21:23:27Z
39,994,877
<p>Closing the socket or removing the file descriptor using <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.remove_reader" rel="nofollow">loop.remove_reader</a> does not notify <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.sock_ac...
1
2016-10-12T09:15:37Z
[ "python", "sockets", "python-asyncio" ]
Extract the string after title in BeautifulSoup
39,986,997
<p>html result is <code>&lt;div class="font-160 line-110" data-container=".snippet container" data-html="true" data-placement="top" data-template='&amp;lt;div class="tooltip infowin-tooltip" role="tooltip"&amp;gt;&amp;lt;div class="tooltip-arrow"&amp;gt;&amp;lt;div class="tooltip-arrow-inner"&amp;gt;&amp;lt;/div&amp;gt...
1
2016-10-11T21:24:47Z
39,987,083
<pre><code>from bs4 import BeautifulSoup myHTML = 'what you posted above' soup = BeautifulSoup(myHTML, "html5lib") title = soup.find('div')['title'] </code></pre> <p>We're just searching for <code>&lt;div&gt;</code> tags here, you'll probably want to be more specific in vivo.</p>
0
2016-10-11T21:30:39Z
[ "python", "html", "beautifulsoup" ]
Extract the string after title in BeautifulSoup
39,986,997
<p>html result is <code>&lt;div class="font-160 line-110" data-container=".snippet container" data-html="true" data-placement="top" data-template='&amp;lt;div class="tooltip infowin-tooltip" role="tooltip"&amp;gt;&amp;lt;div class="tooltip-arrow"&amp;gt;&amp;lt;div class="tooltip-arrow-inner"&amp;gt;&amp;lt;/div&amp;gt...
1
2016-10-11T21:24:47Z
39,987,238
<p>Slightly safer way than the other answer</p> <pre><code>from bs4 import BeautifulSoup myHTML = 'what you posted above' soup = BeautifulSoup(myHTML, "html5lib") div = soup.find('div') title = div.get('title', '') # safe way to check for the title, incase the div doesn't contain it </code></pre>
0
2016-10-11T21:42:42Z
[ "python", "html", "beautifulsoup" ]
Extract the string after title in BeautifulSoup
39,986,997
<p>html result is <code>&lt;div class="font-160 line-110" data-container=".snippet container" data-html="true" data-placement="top" data-template='&amp;lt;div class="tooltip infowin-tooltip" role="tooltip"&amp;gt;&amp;lt;div class="tooltip-arrow"&amp;gt;&amp;lt;div class="tooltip-arrow-inner"&amp;gt;&amp;lt;/div&amp;gt...
1
2016-10-11T21:24:47Z
39,987,712
<p>You should use the class or some attribute to select the div, calling <code>find("div")</code> would select the first div on the page, also <em>title</em> is an attribute not a tag so you need to access the <em>title attribute</em> once you locate the tag. A few of examples of how to be specific and extract the <em...
1
2016-10-11T22:24:10Z
[ "python", "html", "beautifulsoup" ]
Creating dynamic variables for XML Parsing
39,987,001
<p>I'm incredibly new at this, and I've tried searching but nothing I've found has been able to work for me.</p> <p>I have xml data that looks like this</p> <pre><code>&lt;datainfo&gt; &lt;data&gt; &lt;info State="1" Reason="x" Start="01/01/2016 00:00:00.000" End="01/01/2016 02:00:00.000"&gt;&lt;/info&gt; ...
2
2016-10-11T21:25:06Z
39,987,458
<p>This is assuming you have your xml parsed into an array of arrays</p> <pre><code>import csv # This is assuming you have your xml parsed into an array of arrays [['state', 'reason'], ['state', 'reason']] # example of array format data = [['1', 'x'], ['1', 'y'], ['2', 'z']] with open("output.csv", "w") as f: w...
0
2016-10-11T21:59:54Z
[ "python", "xml", "python-3.x", "parsing", "lxml" ]
Creating dynamic variables for XML Parsing
39,987,001
<p>I'm incredibly new at this, and I've tried searching but nothing I've found has been able to work for me.</p> <p>I have xml data that looks like this</p> <pre><code>&lt;datainfo&gt; &lt;data&gt; &lt;info State="1" Reason="x" Start="01/01/2016 00:00:00.000" End="01/01/2016 02:00:00.000"&gt;&lt;/info&gt; ...
2
2016-10-11T21:25:06Z
39,988,022
<p>You can use a <em>defaultdict</em> for recurring keys using lists as value, you can also filter the info nodes using an <em>xpath</em> to only find the nodes that have both of the <em>attributes</em> you want so no need for any except:</p> <pre><code>x = """&lt;datainfo&gt; &lt;data&gt; &lt;info State="1...
1
2016-10-11T22:55:11Z
[ "python", "xml", "python-3.x", "parsing", "lxml" ]
Natural language date differences in python
39,987,036
<p>I have a dynamically generated pandas dataframe with this structure:</p> <pre><code>name,Events,Last,Elapsed 10.0.0.103,11230,2016-10-11 23:16:45,0 days 00:00:08.708000000 10.0.0.24,14088,2016-10-11 23:16:52,0 days 00:00:01.708000000 </code></pre> <p>This details the number of events per IP address (name), when th...
0
2016-10-11T21:27:20Z
40,000,835
<p>Thanks to @Boud for getting me started.</p> <p>CSV:</p> <pre><code>name,Events,Last,Elapsed 10.0.0.103,11230,2016-10-11 23:16:45,0 days 00:00:08.708000000 10.0.0.24,14088,2016-10-11 23:16:52,0 days 00:00:01.708000000 </code></pre> <p>Using texttime.py (<a href="http://code.activestate.com/recipes/498062-nicely-re...
0
2016-10-12T14:10:04Z
[ "python", "pandas", "python-datetime" ]
Plotting a dataframe as both a 'hist' and 'kde' on the same plot
39,987,071
<p>I have a pandas <code>dataframe</code> with user information. I would like to plot the age of users as both a <code>kind='kde'</code> and on <code>kind='hist'</code> on the same plot. At the moment I am able to have the two separate plots. The dataframe resembles:</p> <pre><code>member_df= user_id Age 1 ...
4
2016-10-11T21:29:35Z
39,987,117
<p><code>pd.DataFrame.plot()</code> returns the <code>ax</code> it is plotting to. You can reuse this for other plots.</p> <p>Try:</p> <pre><code>ax = member_df.Age.plot(kind='kde') member_df.Age.plot(kind='hist', bins=40, ax=ax) ax.set_xlabel('Age') </code></pre> <p><strong><em>example</em></strong><br> I plot <co...
6
2016-10-11T21:33:28Z
[ "python", "pandas", "matplotlib", "plot" ]
simultaneous fitting python parameter sharing
39,987,105
<p>I have six datasets, I wish to fit all six datasets simultaneously, with two parameters common between the six datasets and one to be fit seperately.</p> <p>I'm planning to fit a simple ax**2+bx+c polynomial to the datasets, where a and b is shared between the six datasets and the offset, c, is not shared between t...
0
2016-10-11T21:32:37Z
39,996,509
<p>One possibility is to change the function to be fitted so that each data set has its own "a" and "b" parameter with a common "c", similar to this crude code snippet:</p> <pre><code>def func(x,a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6, c): if x in data_set_1: return (a1*(x**2)+b1*x+c) if x in data_set_2: ...
0
2016-10-12T10:37:49Z
[ "python", "curve-fitting", "least-squares", "data-fitting" ]
simultaneous fitting python parameter sharing
39,987,105
<p>I have six datasets, I wish to fit all six datasets simultaneously, with two parameters common between the six datasets and one to be fit seperately.</p> <p>I'm planning to fit a simple ax**2+bx+c polynomial to the datasets, where a and b is shared between the six datasets and the offset, c, is not shared between t...
0
2016-10-11T21:32:37Z
39,998,622
<p>Because I had similar fitting problems, I made <a href="http://symfit.readthedocs.io/en/latest/fitting_types.html#global-fitting" rel="nofollow"><code>symfit</code></a> to deal with this kind of scenario. So I'm sorry for shamelessly suggesting my own package but I think it would be very helpful for you. It wraps cu...
0
2016-10-12T12:26:39Z
[ "python", "curve-fitting", "least-squares", "data-fitting" ]
simultaneous fitting python parameter sharing
39,987,105
<p>I have six datasets, I wish to fit all six datasets simultaneously, with two parameters common between the six datasets and one to be fit seperately.</p> <p>I'm planning to fit a simple ax**2+bx+c polynomial to the datasets, where a and b is shared between the six datasets and the offset, c, is not shared between t...
0
2016-10-11T21:32:37Z
40,020,042
<p>Thanks for all the suggestions, I seem to have found a way to fit them simultaneously with a,b and c1,c2,c3,c4,c5,c6 as the parameters, where a and b are shared.</p> <p>Below is the code I used in the end:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit x=[vt...
0
2016-10-13T11:44:25Z
[ "python", "curve-fitting", "least-squares", "data-fitting" ]
Django - ManagementForm data is missing or has been tampered with
39,987,145
<p>I've been racking my brain over this problem for the past few days and I've read numerous other questions regarding the same error but they all seem to be different cases (not including management form, forgetting to update TOTAL_FORMS, etc etc) and do not resolve my problem. I have a page which could contain multip...
0
2016-10-11T21:35:03Z
39,989,296
<p>I expected this to be a silly problem and I turned about to be right! When my generic_form_view method creates the formsets on the GET request I was adding a prefix like the documentation mentioned but I was not adding a prefix when creating the formsets on the POST. </p>
0
2016-10-12T01:49:02Z
[ "python", "django", "django-forms" ]
ImportError: cannot import name BayesianGaussianMixture
39,987,374
<p>I am trying to use the Batesian model in <code>sklearn</code> but I get the following error when I try.</p> <pre><code>&gt;&gt;&gt; from sklearn.mixture import BayesianGaussianMixture Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name BayesianGaussia...
0
2016-10-11T21:53:25Z
39,987,425
<p>Update scikit-learn to 0.18, in <a href="http://scikit-learn.org/0.17/modules/classes.html#module-sklearn.mixture" rel="nofollow">previous versions</a> it was called <code>VBGMM</code> (Variational Bayesian Gaussian Mixture Model) - actually it was a bit different method, but it is the closest you will get in previo...
1
2016-10-11T21:57:13Z
[ "python", "machine-learning", "scikit-learn", "cluster-analysis" ]
Python write of scraping data to csv file
39,987,551
<p>I wrote simple code which scrape data from website but i'm struggling to save all rows to csv file. Finished script save only one row - it's last occurance in loop.</p> <pre><code>def get_single_item_data(item_url): f= csv.writer(open("scrpe.csv", "wb")) f.writerow(["Title", "Company", "Price_netto"]) ...
-1
2016-10-11T22:07:26Z
39,988,009
<p>@PadraicCunningham This is my whole script:</p> <pre><code>import requests from bs4 import BeautifulSoup import csv url_klocki = "http://selgros24.pl/Dla-dzieci/Zabawki/Klocki-pc1121.html" r = requests.get(url_klocki) soup = BeautifulSoup(r.content, "html.parser") def main_spider(max_page): page = 1 while...
0
2016-10-11T22:53:53Z
[ "python", "csv" ]
Python write of scraping data to csv file
39,987,551
<p>I wrote simple code which scrape data from website but i'm struggling to save all rows to csv file. Finished script save only one row - it's last occurance in loop.</p> <pre><code>def get_single_item_data(item_url): f= csv.writer(open("scrpe.csv", "wb")) f.writerow(["Title", "Company", "Price_netto"]) ...
-1
2016-10-11T22:07:26Z
39,988,071
<p>The problem is that you are opening the output file in <code>get_single_item_data</code>, and it is getting closed when that function returns and <code>f</code> goes out of scope. You want to pass an open file in to <code>get_single_item_data</code> so multiple rows will be written.</p>
0
2016-10-11T23:01:41Z
[ "python", "csv" ]
Calculating similarity "score" between multiple dictionaries
39,987,596
<p>I have a reference dictionary, "dictA" and I need to compare it (calculate similarity between key and vules) to n amount of dictionaries that are generated on the spot. Each dictionary has the same length. Lets say for the sake of the discussion that the n amount of dictionaries to compare it with is 3: dictB, dictC...
4
2016-10-11T22:11:51Z
39,987,767
<p>Here's a general structure -- assuming that you can generate the dictionaries individually, using each before generating the next. This sounds like what you might want. calculate_similarity would be a function containing your "I have a solution" code above.</p> <pre><code>reference = {'1':"U", '2':"D", '3':"D", '...
1
2016-10-11T22:29:04Z
[ "python", "python-3.x" ]
Calculating similarity "score" between multiple dictionaries
39,987,596
<p>I have a reference dictionary, "dictA" and I need to compare it (calculate similarity between key and vules) to n amount of dictionaries that are generated on the spot. Each dictionary has the same length. Lets say for the sake of the discussion that the n amount of dictionaries to compare it with is 3: dictB, dictC...
4
2016-10-11T22:11:51Z
39,987,842
<p>If you stick your solution in a function, you can call it by name for any two dicts. Also, if you curry the function by breaking up the arguments across nested functions, you can partially apply the first dict to get back a function that just wants the second (or you could use <code>functools.partial</code>), which ...
0
2016-10-11T22:36:26Z
[ "python", "python-3.x" ]
Calculating similarity "score" between multiple dictionaries
39,987,596
<p>I have a reference dictionary, "dictA" and I need to compare it (calculate similarity between key and vules) to n amount of dictionaries that are generated on the spot. Each dictionary has the same length. Lets say for the sake of the discussion that the n amount of dictionaries to compare it with is 3: dictB, dictC...
4
2016-10-11T22:11:51Z
40,000,523
<p>Thanks to everyone for participation on the answer. Here is result that does what I need:</p> <pre><code>def compareTwoDictionaries(self, absolute, reference, listOfDictionaries): #look only for absolute fit, yes or no if (absolute == True): similarity = reference == listOfDictionaries else: ...
0
2016-10-12T13:55:55Z
[ "python", "python-3.x" ]
Calculating similarity "score" between multiple dictionaries
39,987,596
<p>I have a reference dictionary, "dictA" and I need to compare it (calculate similarity between key and vules) to n amount of dictionaries that are generated on the spot. Each dictionary has the same length. Lets say for the sake of the discussion that the n amount of dictionaries to compare it with is 3: dictB, dictC...
4
2016-10-11T22:11:51Z
40,004,171
<p>Based on your problem setup, there appears to be no alternative to looping through the input list of dictionaries. However, there is a multiprocessing trick that can be applied here. </p> <p>Here is your input:</p> <pre><code>dict_a = {'1': "U", '2': "D", '3': "D", '4': "U", '5': "U", '6': "U"} dict_b = {'1': "U",...
1
2016-10-12T16:53:15Z
[ "python", "python-3.x" ]
How to use Mac OS X NSEvents within wxPython application?
39,987,661
<p>I am writing an application that has to react to system wide keypresses on Mac OS X.</p> <p>So I found some key logger examples that should work and hit a wall, because all examples are based on NSSharedApplication() and PyObjC AppHelper.runEventLoop() while my application is written in wxPython.</p> <p>Here I pos...
0
2016-10-11T22:17:27Z
40,044,548
<p>As nobody answered I went searching around with different angle in view.</p> <p>So I discovered that Quartz module can be used to get to keyboard and mouse events. No custom loop needed, therefore wx.App() and wx.App.MainLoop() aren't getting in the way.</p> <p>I also found a nice package named pynput that does ju...
0
2016-10-14T13:36:15Z
[ "python", "osx", "cocoa", "wxpython", "pyobjc" ]
Python scraping via xml prints empty brackets
39,987,672
<p>I am trying to extract just a few characters from a website via lxml, to tree, then xpath. I've tried using google chrome to obtain the correct xpath yet it prints empty brackets.</p> <pre><code> #imports from lxml import html import requests #get magicseaweed Scripps report msScrippsPage = requ...
1
2016-10-11T22:19:06Z
39,987,911
<p>You shouldn't use line break in your url. When you use one line your xpath work.</p> <pre><code>msScrippsPage = requests.get("""http://magicseaweed.com/Scripps-Pier-La-Jolla-Surf-Report/296/.html""") print msScrippsPage.content [' 0.4-0.6', ' '] ######################################## url = """http://magicsea...
2
2016-10-11T22:45:19Z
[ "python", "xml", "xpath", "web-scraping" ]
How to display custom python QTextEdit effects like underline in txt or rtf format?
39,987,702
<p>I'm having a problem where when I save the text from QTextEdit as a txt, or rtf, it doesnt save things like underline and font size. Here's the code:</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING!...
-1
2016-10-11T22:22:14Z
39,989,011
<p>It's because you're converting the text to <em>plain text</em> with <code>toPlainText</code>, which doesn't contain any formatting information.</p> <pre><code>yourFile.write(str(self.textEdit.toPlainText())) </code></pre> <p>If you want to maintain the formatting, you need to use <code>toHtml</code>. </p> <pre><...
1
2016-10-12T01:07:33Z
[ "python", "pyqt", "pyqt4" ]
Python - Convert dictionary into list with length based on values
39,987,708
<p>I have a dictionary</p> <pre><code>d = {1: 3, 5: 6, 10: 2} </code></pre> <p>I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.</p> <p>I've written this code that does the job:</p> <pre><code>d = {1: 3, 5: 6, 10: 2} l = [] for i...
3
2016-10-11T22:23:24Z
39,987,735
<p>One approach is to use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> to glue sublists together</p> <pre><code>&gt;&gt;&gt; list(itertools.chain(*[[k]*v for k, v in d.items()])) [1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5] </code></pre> <p>Or if ...
1
2016-10-11T22:26:13Z
[ "python", "list", "dictionary" ]
Python - Convert dictionary into list with length based on values
39,987,708
<p>I have a dictionary</p> <pre><code>d = {1: 3, 5: 6, 10: 2} </code></pre> <p>I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.</p> <p>I've written this code that does the job:</p> <pre><code>d = {1: 3, 5: 6, 10: 2} l = [] for i...
3
2016-10-11T22:23:24Z
39,987,749
<p><code>[k for k,v in d.items() for _ in range(v)]</code> ... I guess...</p> <p>if you want it sorted you can do</p> <p><code>[k for k,v in sorted(d.items()) for _ in range(v)]</code></p>
1
2016-10-11T22:27:01Z
[ "python", "list", "dictionary" ]
Python - Convert dictionary into list with length based on values
39,987,708
<p>I have a dictionary</p> <pre><code>d = {1: 3, 5: 6, 10: 2} </code></pre> <p>I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.</p> <p>I've written this code that does the job:</p> <pre><code>d = {1: 3, 5: 6, 10: 2} l = [] for i...
3
2016-10-11T22:23:24Z
39,987,754
<p>You can do it using a list comprehension:</p> <pre><code>[i for i in d for j in range(d[i])] </code></pre> <p>yields:</p> <pre><code>[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5] </code></pre> <p>You can sort it again to get the list you were looking for.</p>
2
2016-10-11T22:27:29Z
[ "python", "list", "dictionary" ]
Why does BeautifulSoup work the second time parsing, but not the first
39,987,731
<p>This is the <code>ResultSet</code> of running <code>soup[0].find_all('div', {'class':'font-160 line-110'})</code>: </p> <pre><code>[&lt;div class="font-160 line-110" data-container=".snippet-container" data-html="true" data-placement="top" data-template='&amp;lt;div class="tooltip infowin-tooltip" role="tooltip"&a...
2
2016-10-11T22:25:49Z
39,988,337
<p>You use wrong selection.</p> <p>Selection <code>soup[0].find_all('div', {'class':'font-160 line-110'})</code> finds <code>&lt;div&gt;</code> and you can even see <code>&lt;div&gt;</code> when you print it. But when you add <code>.find()</code> it starts searching <strong>inside</strong> <code>&lt;div&gt;</code> - s...
0
2016-10-11T23:33:55Z
[ "python", "html", "beautifulsoup" ]
Why does BeautifulSoup work the second time parsing, but not the first
39,987,731
<p>This is the <code>ResultSet</code> of running <code>soup[0].find_all('div', {'class':'font-160 line-110'})</code>: </p> <pre><code>[&lt;div class="font-160 line-110" data-container=".snippet-container" data-html="true" data-placement="top" data-template='&amp;lt;div class="tooltip infowin-tooltip" role="tooltip"&a...
2
2016-10-11T22:25:49Z
39,998,044
<p>I found out the problem occurred when I set up my BeautifulSoup. I created a list of partial search results then had to iterate over the list to research it. I fixed this by just searching for what I wanted in on line: </p> <p>I changed:</p> <pre><code>soup = [] with i in range(2) #number of pages parsed ...
1
2016-10-12T11:58:45Z
[ "python", "html", "beautifulsoup" ]
How to read values from from a text file with columns?
39,987,756
<p>I'm trying to read data from a file that is separated in columns with data from each year and lines with the name of the values (eg:number of times I opened Firefox on the year 2015). Now, I know how to read a specific line but I'm having trouble reading from the different columns. They are 10 spaces wide but only h...
0
2016-10-11T22:27:52Z
39,987,782
<p>If you know how many columns you are going to have you can split the whitespace and coerce to a float:</p> <pre><code>[float(i) for i in "-3.5 1.0 -2.9 6.8".split()] </code></pre> <p>Yields:</p> <pre><code>[-3.5, 1.0, -2.9, 6.8] </code></pre>
0
2016-10-11T22:30:43Z
[ "python", "slice" ]
How to read values from from a text file with columns?
39,987,756
<p>I'm trying to read data from a file that is separated in columns with data from each year and lines with the name of the values (eg:number of times I opened Firefox on the year 2015). Now, I know how to read a specific line but I'm having trouble reading from the different columns. They are 10 spaces wide but only h...
0
2016-10-11T22:27:52Z
39,987,803
<p>Once you've got your line in a string, the simplest would be to split the string on the whitespace.</p> <pre><code>values = line.split() </code></pre> <p>The iterate through that list and cast to a float.</p> <pre><code>float_values = [float(v) for v in values] </code></pre>
0
2016-10-11T22:32:40Z
[ "python", "slice" ]
Serving two Django sites with WSGI results in internal server error for only one of the sites
39,987,844
<p>I have a Django site and a Django CMS site which I am serving from the same ubuntu 14.04 server running MySQL 5.6, Apache2 2.4.7 and Django 1.8 via mod_wsgi version 4.5.7 using virtual hosts. Locally (on my Linux PC) I have managed to accomplish this with both sites working perfectly and hence decided to migrate to ...
0
2016-10-11T22:36:39Z
39,988,240
<p>This is caused by your database or some other resource needed during initialisation of Django not being available, or Django initialisation otherwise failing in some other way the first time. Back in time the initialisation of Django was reentrant and could be called a second time if the first time it failed. This i...
1
2016-10-11T23:20:02Z
[ "python", "django", "mod-wsgi", "django-cms" ]
Serving two Django sites with WSGI results in internal server error for only one of the sites
39,987,844
<p>I have a Django site and a Django CMS site which I am serving from the same ubuntu 14.04 server running MySQL 5.6, Apache2 2.4.7 and Django 1.8 via mod_wsgi version 4.5.7 using virtual hosts. Locally (on my Linux PC) I have managed to accomplish this with both sites working perfectly and hence decided to migrate to ...
0
2016-10-11T22:36:39Z
40,065,477
<p>Adding <code>startup-timeout=15</code> to <code>WSGIDaemonProcess</code> in the virtual hosts config file did not solve my issue.</p> <p>As for the "earlier error message in the error log" with the modified <code>wsgi.py</code> to get the real error, the only errors present in the <code>/var/log/apache2/cms-error.l...
0
2016-10-16T00:04:22Z
[ "python", "django", "mod-wsgi", "django-cms" ]
python lists in a list
39,987,852
<p>I have a simple question. I know how to bring out(I don't know how to say besides 'bring out') from a list. for example,</p> <pre><code>Alist = [ 1, 2, 3, 4 ] </code></pre> <p>Then,</p> <pre><code>Alist[0] = 1 Alist[1] = 2 </code></pre> <p>But, what if</p> <pre><code>Blist = [[1, 2, 3 ,4], [5, 6, 7]] Blist[0] =...
0
2016-10-11T22:37:38Z
39,987,871
<p><strong>Blist[1]</strong> is a list itself. To get the head element, use an index on <strong>Blist[1]</strong></p> <pre><code>Blist[1][0] </code></pre>
2
2016-10-11T22:39:36Z
[ "python", "python-3.x" ]
python lists in a list
39,987,852
<p>I have a simple question. I know how to bring out(I don't know how to say besides 'bring out') from a list. for example,</p> <pre><code>Alist = [ 1, 2, 3, 4 ] </code></pre> <p>Then,</p> <pre><code>Alist[0] = 1 Alist[1] = 2 </code></pre> <p>But, what if</p> <pre><code>Blist = [[1, 2, 3 ,4], [5, 6, 7]] Blist[0] =...
0
2016-10-11T22:37:38Z
39,987,883
<p>You know that <code>B[1]</code> gets you a reference to the second list in <code>B</code>.</p> <pre><code>lst = B[1] </code></pre> <p>You can index that result again to get another element</p> <pre><code>lst[0] </code></pre> <p>However you can of course do this more easily in one line</p> <pre><code>B[1][0] </c...
3
2016-10-11T22:40:57Z
[ "python", "python-3.x" ]
Update Pandas Cells based on Column Values and Other Columns
39,987,860
<p>I am looking to update many columns based on the values in one column; this is easy with a loop but takes far too long for my application when there are many columns and many rows. What is the most elegant way to get the desired counts for each letter?</p> <p>Desired Output:</p> <pre><code> Things count_...
3
2016-10-11T22:38:13Z
39,987,904
<p><strong><em>option 1</em></strong><br> <code>apply</code> + <code>value_counts</code></p> <pre><code>s = pd.Series([list('ABC'), list('AAA'), list('BA'), list('DD')], name='Things') pd.concat([s, s.apply(lambda x: pd.Series(x).value_counts()).fillna(0)], axis=1) </code></pre> <p><a href="https://i.stack.imgur.com...
1
2016-10-11T22:44:04Z
[ "python", "pandas", "apply" ]
Update Pandas Cells based on Column Values and Other Columns
39,987,860
<p>I am looking to update many columns based on the values in one column; this is easy with a loop but takes far too long for my application when there are many columns and many rows. What is the most elegant way to get the desired counts for each letter?</p> <p>Desired Output:</p> <pre><code> Things count_...
3
2016-10-11T22:38:13Z
39,988,409
<p>The most elegant is definitely the CountVectorizer from sklearn. </p> <p>I'll show you how it works first, then I'll do everything in one line, so you can see how elegant it is. </p> <h3>First, we'll do it step by step:</h3> <p>let's create some data</p> <pre><code>raw = ['ABC', 'AAA', 'BA', 'DD'] things = [lis...
3
2016-10-11T23:41:32Z
[ "python", "pandas", "apply" ]
Count duplicates in list and assign the sum into list
39,987,877
<p>I have a list with duplicate strings:</p> <pre><code>lst = ["abc", "abc", "omg", "what", "abc", "omg"] </code></pre> <p>and I would like to produce:</p> <pre><code>lst = ["3 abc", "2 omg", "what"] </code></pre> <p>so basically count duplicates, remove duplicates and add the sum to the beginning of the string.</p...
3
2016-10-11T22:40:20Z
39,987,937
<p>It seems you are needlessly complicating things. Here is a very Pythonic approach:</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; class OrderedCounter(collections.Counter, collections.OrderedDict): ... pass ... &gt;&gt;&gt; lst = ["abc", "abc", "omg", "what", "abc", "omg"] &gt;&gt;&gt; counts = Orde...
5
2016-10-11T22:47:09Z
[ "python" ]
Count duplicates in list and assign the sum into list
39,987,877
<p>I have a list with duplicate strings:</p> <pre><code>lst = ["abc", "abc", "omg", "what", "abc", "omg"] </code></pre> <p>and I would like to produce:</p> <pre><code>lst = ["3 abc", "2 omg", "what"] </code></pre> <p>so basically count duplicates, remove duplicates and add the sum to the beginning of the string.</p...
3
2016-10-11T22:40:20Z
39,987,952
<p>You've properly used the Counter type to accumulate the needed values. Now, it's just a matter of a more Pythonic way to generate the results. Most of all, pull the initialization out of the loop, or you'll lose all but the last entry.</p> <pre><code>list2 = [] for tpl in have: count = "" if tpl[1] == 0 else ...
1
2016-10-11T22:48:10Z
[ "python" ]
Count duplicates in list and assign the sum into list
39,987,877
<p>I have a list with duplicate strings:</p> <pre><code>lst = ["abc", "abc", "omg", "what", "abc", "omg"] </code></pre> <p>and I would like to produce:</p> <pre><code>lst = ["3 abc", "2 omg", "what"] </code></pre> <p>so basically count duplicates, remove duplicates and add the sum to the beginning of the string.</p...
3
2016-10-11T22:40:20Z
39,988,073
<p>Try this:</p> <pre><code>lst = ["abc", "abc", "omg", "what", "abc", "omg"] l = [lst.count(i) for i in lst] # Count number of duplicates d = dict(zip(lst, l)) # Convert to dictionary lst = [str(d[i])+' '+i if d[i]&gt;1 else i for i in d] # Convert to list of strings </code></pre>
1
2016-10-11T23:01:50Z
[ "python" ]
Count duplicates in list and assign the sum into list
39,987,877
<p>I have a list with duplicate strings:</p> <pre><code>lst = ["abc", "abc", "omg", "what", "abc", "omg"] </code></pre> <p>and I would like to produce:</p> <pre><code>lst = ["3 abc", "2 omg", "what"] </code></pre> <p>so basically count duplicates, remove duplicates and add the sum to the beginning of the string.</p...
3
2016-10-11T22:40:20Z
39,988,461
<p>Another possible solution with comments to help...</p> <pre><code>import operator #list lst = ["abc", "abc", "omg", "what", "abc", "omg"] #dictionary countDic = {} #iterate lst to populate dictionary: {'what': 1, 'abc': 3, 'omg': 2} for i in lst: if i in countDic: countDic[i] += 1 else: c...
1
2016-10-11T23:47:27Z
[ "python" ]
Python equivalent of SQL: SELECT w/ MAX() and GROUP BY
39,987,920
<p>I have data like this:</p> <pre><code>df = pd.DataFrame( { 'ID': [1,1,2,3,3,3,4], 'SOME_NUM': [8,10,2,4,0,5,1] } ); df ID SOME_NUM 0 1 8 1 1 10 2 2 2 3 3 4 4 3 0 5 3 5 6 4 1 </code></pre> <p>And I want to group by the ID column while retaining the maximum v...
2
2016-10-11T22:46:07Z
39,987,983
<p>Seeing as how you are using Pandas... use the groupby functionality baked in</p> <pre><code>df.groupby("ID").max() </code></pre>
3
2016-10-11T22:51:40Z
[ "python", "sql", "pandas", "group-by", "max" ]
What is the origin/etymology of Matplotlib's symlog (a.k.a. symmetrical log) scale?
39,988,048
<p>This is not really a programming question. Rather a historical one...</p> <hr> <p>I am wondering about Matplotlib's <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.yscale" rel="nofollow"><em>symlog</em></a> or "symmetrical log" scale:</p> <ul> <li>Is it a Matplotlib invention?</li> <li>Has an...
-2
2016-10-11T22:59:09Z
39,988,706
<p>1) You would have to ask <a href="https://github.com/mdboom" rel="nofollow">mdboom</a>, who appears to have authored the relevant class (according to git blame), which is </p> <p>2) SymmetricalLogScale.</p> <p>Matplotlib has a github, and has been under version control for some time, so these questions are easily ...
-1
2016-10-12T00:23:08Z
[ "python", "matplotlib", "plot", "scale", "logarithm" ]
Find subarray that sums to given value in Python
39,988,052
<p>If I am given a subarray [1,2,3,4] and a value 8. I want to return the subarray [1,3,4]. I have a bug in my code and am not sure how to fix it since I am new to recursion. I have my Python code below. I am getting back the value [3,4] to print which is obviously not the correct answer. How do I get my first element ...
0
2016-10-11T22:59:43Z
39,988,197
<p>Do you need <strong>any</strong> subarray that matches your sum? or <strong>all</strong> subarrays? (Or the shortest, or the longest?) The proper answer is going to be highly dependent on this.</p> <p>BTW, this is a varient of the knapsack problem: <a href="https://en.wikipedia.org/wiki/Knapsack_problem" rel="no...
1
2016-10-11T23:14:40Z
[ "python", "recursion", "sub-array" ]
Find subarray that sums to given value in Python
39,988,052
<p>If I am given a subarray [1,2,3,4] and a value 8. I want to return the subarray [1,3,4]. I have a bug in my code and am not sure how to fix it since I am new to recursion. I have my Python code below. I am getting back the value [3,4] to print which is obviously not the correct answer. How do I get my first element ...
0
2016-10-11T22:59:43Z
39,988,518
<p>The immediate problem is that you append a[0] to sa at the top of the function, but later destroy that with the return value from a sub-call. To patch this, add a clause before you return the final result:</p> <pre><code> except: sa = [] # i put this here because I want to erase the incorrect array if d...
1
2016-10-11T23:55:40Z
[ "python", "recursion", "sub-array" ]
Find subarray that sums to given value in Python
39,988,052
<p>If I am given a subarray [1,2,3,4] and a value 8. I want to return the subarray [1,3,4]. I have a bug in my code and am not sure how to fix it since I am new to recursion. I have my Python code below. I am getting back the value [3,4] to print which is obviously not the correct answer. How do I get my first element ...
0
2016-10-11T22:59:43Z
39,988,549
<p>I made a recursive solution that works, hope it helps:</p> <pre><code>def main(): success, solution = WeightChecker((1,2,3,4)).check(8) print solution class WeightChecker(object): def __init__(self, to_check): self._to_check = to_check def check(self, weight): return self._check((),...
1
2016-10-12T00:00:32Z
[ "python", "recursion", "sub-array" ]
Implementing softmax regression
39,988,084
<p>I am trying to make a neural network using softmax regression. I am using the following regression formula:</p> <p><a href="https://i.stack.imgur.com/oaAL7.png" rel="nofollow"><img src="https://i.stack.imgur.com/oaAL7.png" alt="enter image description here"></a></p> <p>Lets say I have an input of 1000x100. In othe...
2
2016-10-11T23:03:12Z
39,988,320
<p>If you are training Neural Networks, it might we worth while to check <a href="http://deeplearning.net/tutorial/mlp.html" rel="nofollow">Theano</a> library. It features various output thresholding functions like <em>tanh</em>, <em>softmax</em>, etc. and allows training of neural networks on GPU.</p> <p>Also x^n is ...
1
2016-10-11T23:31:28Z
[ "python", "neural-network", "softmax" ]