title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
AsyncHTTPClient blocking my Tornado IOLoop
38,379,630
<p>how are you?</p> <p>I've been through this trouble the last days, and I seem to not being able to completely understand the tornado gen library.</p> <p>I have this piece of code, as an example:</p> <pre><code>@gen.coroutine def get(self, build_id=None): status_query = self.get_query_arguments("status") li...
1
2016-07-14T16:34:11Z
38,382,907
<blockquote> <p>If your requests aren't IO bound then you won't see much change. - <a href="http://stackoverflow.com/questions/38379630/asynchttpclient-blocking-my-tornado-ioloop?noredirect=1#comment64170452_38379630">Me</a></p> </blockquote> <p>In programming these are the primary limits that we have:</p> <ul> <li...
1
2016-07-14T19:40:26Z
[ "python", "tornado", "coroutine" ]
How to create a list of strings in python from two "array.flatten()"-ed lists
38,379,679
<p>I'm looking to create the following list in python:</p> <pre><code>list = ["pix420_615", "pix421_615", ... , "pix425_620"] </code></pre> <p>N.B. Where the list is a list of strings, not values.</p> <p>From the following two lists:</p> <pre><code>x= [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420...
2
2016-07-14T16:36:43Z
38,379,756
<p>This should do the trick. <code>zip</code> is the nicest way to do this sort of thing:</p> <pre><code>x = [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425] y = [615, 615, 615, 615, 615...
2
2016-07-14T16:40:14Z
[ "python", "arrays", "string", "list" ]
How to create a list of strings in python from two "array.flatten()"-ed lists
38,379,679
<p>I'm looking to create the following list in python:</p> <pre><code>list = ["pix420_615", "pix421_615", ... , "pix425_620"] </code></pre> <p>N.B. Where the list is a list of strings, not values.</p> <p>From the following two lists:</p> <pre><code>x= [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420...
2
2016-07-14T16:36:43Z
38,379,804
<p>From your lists, </p> <pre><code>map(lambda t: 'pix%s_%s' % t, zip(x, y)) </code></pre> <p>or </p> <pre><code>['pix%s_%s' % t for t in zip(x, y)] </code></pre> <p>However, I notice that the first list is basically <code>[420, ..., 425]</code>, and the second one is <code>[615, ...]</code>, which result in <code>...
3
2016-07-14T16:43:07Z
[ "python", "arrays", "string", "list" ]
How to create a list of strings in python from two "array.flatten()"-ed lists
38,379,679
<p>I'm looking to create the following list in python:</p> <pre><code>list = ["pix420_615", "pix421_615", ... , "pix425_620"] </code></pre> <p>N.B. Where the list is a list of strings, not values.</p> <p>From the following two lists:</p> <pre><code>x= [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420...
2
2016-07-14T16:36:43Z
38,379,827
<p>use <code>map</code> function </p> <pre><code>map(lambda a, b: 'pix{0}_{1}'.format(a,b), x, y) </code></pre>
1
2016-07-14T16:44:27Z
[ "python", "arrays", "string", "list" ]
Turn ForeignKey Objects to ChoicesField
38,379,685
<p>I have a model called <code>Space</code> and it has a field called <code>guest</code>, and the field is a choicefield that takes a single number, lets say <code>3</code> and save it in database. I have another model called <code>Book</code> and among its fields is <code>no_of_persons</code>.</p> <p>Now, is it possi...
0
2016-07-14T16:37:03Z
38,379,969
<p>You can create a custom <code>Book</code> form which accepts a <code>guest</code> instance at construction time and dynamically change the widget for the <code>no_of_persons</code> field with a select box.</p> <p>An example implementation:</p> <pre><code>class BookForm(forms.ModelForm): class Meta: mod...
1
2016-07-14T16:53:14Z
[ "python", "django", "django-models", "django-views" ]
Sending Email With Multiple File Paths From For Loop
38,379,919
<p>New to Python and my only "coding" experience is SQL, so please bare with me.</p> <p>I have a for loop that inserts data from spreadsheets (xlsx files) at a shared location into a database table. After the run is complete I would like to send an email with the processed file names to a distribution list. Now I know...
0
2016-07-14T16:50:36Z
38,380,276
<p>This is pretty simple to capture the files which you used:</p> <pre><code>import xlrd import pymssql import glob import os import shutil import uuid from time import gmtime, strftime path = 'c:\\Test\\' source = glob.glob(os.path.join(path, '*.xls*')) print source if not source: exit() files_used = [] ## t...
2
2016-07-14T17:10:45Z
[ "python" ]
How do I aggregate this data and create a new column with python & pandas?
38,379,966
<p>I am attempting to use pandas to aggregate column data in order to calculate the CPC of ads in my dataset based upon a variable in the dataset such as ad-size, ad-category ad-placement etc. So in the case below I am aggregating the adCost and adClicks grouping by the adSize (Which is a categorical variable of 1-5). ...
1
2016-07-14T16:53:00Z
38,380,068
<p>You should be able to simply use <code>groupby</code>. I don't have your data and I'm not entirely certain I understand your question, but something like the following should work:</p> <pre><code>df['total_cost'] = df.groupby('adSize')['adCost'].transform('sum') df['avg_cost'] = df.groupby('adSize')['adCost'].tran...
2
2016-07-14T16:58:28Z
[ "python", "pandas", "aggregation" ]
Python : Fibonacci sequence using range(x,y,n)
38,380,001
<p>I was interested in finding a way to make a variable that gets a value and store it in another variable then getting a new value.<br> A close practical example is the Fibonacci sequence.<br> I reasonably searched hard through available python code for this sequence.<br> There were tons, most often too cryptic for my...
1
2016-07-14T16:54:53Z
38,380,060
<p>You are running through the lines </p> <pre><code> c = b b = a a = c + b print(a) </code></pre> <p>100 times. So you get the first 100 fibonacci numbers.</p> <p>If you want to print fibonacci numbers up to 100, change the for loop to a while loop as such</p> <pre><code>while (a &lt; 100): c = b ...
5
2016-07-14T16:58:08Z
[ "python", "python-3.x", "range", "fibonacci" ]
scipy.optimize.minimize Jacobian function causes 'Value Error: The truth value of an array with more than one element is ambiguous'
38,380,022
<p>I am using the BFGS method, giving it the negative log likelihood of my squared exponential/RBF kernel, as well as the gradient (Jacobian) of it. Leaving out the gradient, it works fine using first differences - but the </p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous....
1
2016-07-14T16:56:24Z
38,381,347
<p>Look at the side bar. See all those SO questions about that same <code>ValueError</code>?</p> <p>While the circumstances vary, in nearly every case it is the result of using a boolean array in a Python context that expects a scalar boolean.</p> <p>A simple example is</p> <pre><code>In [236]: if np.arange(10)&gt;...
1
2016-07-14T18:13:18Z
[ "python", "machine-learning", "scipy" ]
Custom legend for Seaborn regplot (Python 3)
38,380,036
<p>I've been trying to follow this <a href="http://stackoverflow.com/questions/13303928/how-to-make-custom-legend-in-matplotlib">How to make custom legend in matplotlib</a> SO question but I think a few things are getting lost in translation. I used a custom color mapping for the different classes of points in my plot...
1
2016-07-14T16:57:01Z
38,384,978
<p>According to <a href="http://matplotlib.org/users/legend_guide.html" rel="nofollow">http://matplotlib.org/users/legend_guide.html</a> you have to put to legend function artists which will be labeled. To use <code>scatter_plot</code> individually you have to group by your data by color and plot every data of one colo...
1
2016-07-14T22:03:10Z
[ "python", "matplotlib" ]
EMBED-API, Google analytics, server-side authorization
38,380,081
<p>I can't seem to get the EMBED-API Server-side Authorization demo to work: <a href="https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/" rel="nofollow">https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/</a></p> <p>In the demo it says the following:</p> <blockquote> <p>Once the...
0
2016-07-14T16:59:22Z
38,381,202
<p>It depends on your implementation, but basically you want to run your service account code on your server, and have the access token passed to your client application so it can make authorized requests from the browser.</p> <p>The whole app is open sourced and you can see where the service account code is in the <a...
0
2016-07-14T18:04:16Z
[ "python", "google-analytics-api" ]
EMBED-API, Google analytics, server-side authorization
38,380,081
<p>I can't seem to get the EMBED-API Server-side Authorization demo to work: <a href="https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/" rel="nofollow">https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/</a></p> <p>In the demo it says the following:</p> <blockquote> <p>Once the...
0
2016-07-14T16:59:22Z
39,208,494
<p>Add that code in <code>service-account.py</code> file and upload it on your server using FTP. I saved the code using dreamweaver, updated the path and added following line at the end of the <code>service-account.py</code> file:</p> <pre><code>print get_access_token() </code></pre> <p>Upload .JSON file in same dire...
0
2016-08-29T14:17:16Z
[ "python", "google-analytics-api" ]
Sending list of dicts as value of dict with requests.post going wrong
38,380,086
<p>I have clien-server app. I localized trouble and there logic of this:</p> <p>Client:</p> <pre><code># -*- coding: utf-8 -*- import requests def fixing: response = requests.post('http://url_for_auth/', data={'client_id': 'client_id', 'client_secret':'its_secret', 'grant_type': 'p...
0
2016-07-14T16:59:41Z
38,434,816
<p>Looks like request (because it have x-www-encoded-form default) cant include list of dicts as value for key in dict so... I should use json in this case. Finally I maked this func:</p> <pre><code>import requests import json def fixing: response = requests.post('http://url_for_auth/', data={'client_id': 'clien...
0
2016-07-18T10:50:04Z
[ "python", "django", "post", "python-requests", "oauth2" ]
Django: "Invalid default value" during "migrate" command
38,380,166
<p>There is a simple model</p> <pre><code>class Baz(models.Model): FOO = ('foo', 'Foo') BAR = ('bar', 'Bar') FOO_BAR = (FOO, BAR) foo_bar = models.CharField(max_length=5, default=FOO, choices=FOO_BAR) </code></pre> <p>After making migrations via <code>python manage.py makemigrations</code>, when trying to mi...
0
2016-07-14T17:03:46Z
38,380,196
<p>You shouldn't point to thee variable as default value, you should provide the real value that will be saved:</p> <pre><code>foo_bar = models.CharField(max_length=5, default='foo', choices=FOO_BAR) </code></pre>
2
2016-07-14T17:05:43Z
[ "python", "django", "django-models" ]
How to do arithmetic on imported array in python?
38,380,170
<p>I am new to python and only a student so if this question is extremely trivial I apologize</p> <p>I've imported a .csv file and indexed 2 columns using panda using the following:</p> <pre><code>data_AM = pd.read_csv(name_AM, header = None, names = None, usecols = [2,4]) </code></pre> <p>I want to subtract column ...
-1
2016-07-14T17:03:50Z
38,382,661
<p>Try this:</p> <pre><code>data_AM.iloc[:, 2].astype('float64').subtract(data_AM.iloc[:,4].astype('float64')) </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>.astype('float64')</code></a> will convert the datatype of the column to float....
0
2016-07-14T19:27:15Z
[ "python", "pandas" ]
Create a dictionary from a two dimensional list in Python
38,380,237
<p>i'm facing some troubles to create a dictionary from a list and a list of lists. Here's an example:</p> <pre><code>a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] </code></pre> <p>I want a output using the elements of list <strong><em>a</em></strong> and the third element of list <strong><em>b</em><...
0
2016-07-14T17:08:31Z
38,380,250
<p>You could do:</p> <pre><code>dict(zip(a, (x[-1] for x in b))) # Maybe x[2] if some of the sublists have more than 3 elements. </code></pre> <p>If you are on python2.x, you might want to use <code>itertools.izip</code> or <a href="https://docs.python.org/2/library/future_builtins.html" rel="nofollow"><code>future_...
2
2016-07-14T17:09:18Z
[ "python", "list", "dictionary" ]
Create a dictionary from a two dimensional list in Python
38,380,237
<p>i'm facing some troubles to create a dictionary from a list and a list of lists. Here's an example:</p> <pre><code>a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] </code></pre> <p>I want a output using the elements of list <strong><em>a</em></strong> and the third element of list <strong><em>b</em><...
0
2016-07-14T17:08:31Z
38,380,307
<p>I've tried this one and it seemed to have worked:</p> <pre><code>&gt;&gt;&gt; a = ['a','b','c','d'] &gt;&gt;&gt; b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] &gt;&gt;&gt; c = dict(zip(a, [d[2] for d in b])) &gt;&gt;&gt; c {'a': 0, 'c': 0, 'b': 1, 'd': 1} </code></pre>
0
2016-07-14T17:12:44Z
[ "python", "list", "dictionary" ]
Create a dictionary from a two dimensional list in Python
38,380,237
<p>i'm facing some troubles to create a dictionary from a list and a list of lists. Here's an example:</p> <pre><code>a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] </code></pre> <p>I want a output using the elements of list <strong><em>a</em></strong> and the third element of list <strong><em>b</em><...
0
2016-07-14T17:08:31Z
38,380,356
<p>Or, using a dictionary in comprehension:</p> <pre><code>a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] c = {k: v[-1] for k, v in zip(a, b)} </code></pre> <p>See <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">PEP274</a> Dict Comprehensions</p>
1
2016-07-14T17:15:20Z
[ "python", "list", "dictionary" ]
Create a dictionary from a two dimensional list in Python
38,380,237
<p>i'm facing some troubles to create a dictionary from a list and a list of lists. Here's an example:</p> <pre><code>a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] </code></pre> <p>I want a output using the elements of list <strong><em>a</em></strong> and the third element of list <strong><em>b</em><...
0
2016-07-14T17:08:31Z
38,380,572
<p>You can make use of <code>itemgetter</code> inside the <code>operator</code> module. Where <strong>2</strong> represents the index within the <em>b</em> sublists.</p> <pre><code>from operator import itemgetter a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] c = dict(zip(a, map(itemgetter(2), b))) </...
0
2016-07-14T17:28:06Z
[ "python", "list", "dictionary" ]
VBA ADO reference User-Defined error
38,380,262
<p>little background on what I'm trying to accomplish I'm writing a vba script that executes within my Python code to query SQL. I've been stuck and doing research on this ADO.Recordset that keeps giving me a 'User-defined error' I've added all of the required references(to my knowledge)to the code being called out by ...
0
2016-07-14T17:09:58Z
38,384,006
<p>You don't need to add any references if you use late binding:</p> <pre><code>sCode = '''Sub Download_Standard_BOM() 'Initializes variables Dim cnn As Object: Set cnn = CreateObject("ADODB.Connection") Dim rst As Object: Set rst = CreateObject("ADODB.Recordset") Dim ConnectionString As String Dim StrQuery As Stri...
0
2016-07-14T20:49:47Z
[ "python", "excel", "vba", "excel-vba", "adodb" ]
VBA ADO reference User-Defined error
38,380,262
<p>little background on what I'm trying to accomplish I'm writing a vba script that executes within my Python code to query SQL. I've been stuck and doing research on this ADO.Recordset that keeps giving me a 'User-defined error' I've added all of the required references(to my knowledge)to the code being called out by ...
0
2016-07-14T17:09:58Z
38,385,325
<p>Alternatively, you can use Python directly to connect to SQL Server (no COM interface) and output data into csv or Excel format (the latter using <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>, Python's data analysis package):</p> <p>Below is the CSV and ODBC DRIVER approach:</p> <pre><code>import p...
1
2016-07-14T22:38:10Z
[ "python", "excel", "vba", "excel-vba", "adodb" ]
DS201 Cassandra killrvideo - Python Driver and Nodes
38,380,284
<p>Environment: DSE DS201 VM </p> <p>Error 1: Exercise 5 : Drivers.ipynb <a href="http://i.stack.imgur.com/r6fYj.png" rel="nofollow">enter image description here</a></p> <p>While trying to use the Python driver to connect to Cassandra.</p> <pre><code> from cassandra.cluster import Cluster cluster = Cluster()...
0
2016-07-14T17:11:06Z
38,461,392
<p>So finally I resolved this. The issue was with the Python drivers</p>
0
2016-07-19T14:29:40Z
[ "python", "cassandra", "datastax", "datastax-enterprise" ]
Potential Exceptions using builtin str() type in Python
38,380,335
<p>When working with built-in types like <code>int</code> and <code>float</code> in Python, it's common to employ exception handling in cases where input might be unreliable:</p> <pre><code>def friendly_int_convert(val): "Convert value to int or return 37 &amp; print an alert if conversion fails" try: ...
4
2016-07-14T17:14:23Z
38,380,769
<p>There's a huge difference between <code>str</code> and <code>int</code> in this regard. <code>int</code> can definitely raise <code>TypeError</code> and <code>ValueError</code>.</p> <p>As far as I can think, the only exception that <code>str</code> can raise for normal objects is <code>UnicodeEncodeError</code>:</...
1
2016-07-14T17:39:51Z
[ "python", "string", "python-3.x", "exception-handling", "built-in" ]
Potential Exceptions using builtin str() type in Python
38,380,335
<p>When working with built-in types like <code>int</code> and <code>float</code> in Python, it's common to employ exception handling in cases where input might be unreliable:</p> <pre><code>def friendly_int_convert(val): "Convert value to int or return 37 &amp; print an alert if conversion fails" try: ...
4
2016-07-14T17:14:23Z
38,380,815
<blockquote> <p>In summary: Is it generally safe to use <code>str()</code> without a <code>try</code> / <code>except</code> block even with unreliable input?</p> </blockquote> <p>That depends on what kind of input we're talking about. You've tagged this question Python 3, so you don't need to worry about the Unicode...
2
2016-07-14T17:43:12Z
[ "python", "string", "python-3.x", "exception-handling", "built-in" ]
Potential Exceptions using builtin str() type in Python
38,380,335
<p>When working with built-in types like <code>int</code> and <code>float</code> in Python, it's common to employ exception handling in cases where input might be unreliable:</p> <pre><code>def friendly_int_convert(val): "Convert value to int or return 37 &amp; print an alert if conversion fails" try: ...
4
2016-07-14T17:14:23Z
38,381,020
<p>Due to concerns you've raised, I'd do <code>except Exception as e:</code>. <code>Exception</code> is generic "catch-all" in Python 3 for "normal" exceptions (other than "system-level" exceptions resulting from process getting signals, <code>KeyboardInterrupt</code>, etc).</p> <p>If I were you I'd log the actual exc...
1
2016-07-14T17:54:08Z
[ "python", "string", "python-3.x", "exception-handling", "built-in" ]
How to redirect with params that are not shown in url?
38,380,336
<p>I have a Flask app, and view like this:</p> <pre><code>@app.route("/", methods=('POST', 'GET')) def index(): ... return redirect(url_for( 'checkout', data=json.dumps(data['data']), source=source), code=307 ) @app.route("/checkout", methods=('POST', 'GET')) def checkout()...
1
2016-07-14T17:14:35Z
38,412,282
<p>You get these parameters because you explicitly tell flask to generate them:</p> <p><code>url_for("checkout", data=..., source=...)</code> creates the url to the checkout view includeing the parameters "data" and "source". If you don't want them leave them out.</p> <p>But I see that you need to pass some data arou...
1
2016-07-16T14:42:57Z
[ "python", "flask" ]
Specifying a large commented header using astropy.tables module
38,380,424
<p>N.B. I'm using a combination of astropy's Table and ascii modules.</p> <p>I'm looking to include the following commented header above my table:</p> <pre><code>#1 pxlname 1 #2 x 0 #3 y 0 #4 z 8 #5 Dist 9 #6 FUV 6 FUV #7 UVW2 ...
0
2016-07-14T17:18:52Z
38,384,134
<p>Something like this:</p> <pre><code>In [29]: t = Table([[1],[1]], names=('##pxlname', 'x')) In [30]: t.meta['comments'] = ['1 pxlname 1', '2 x 0'] # you define these. In [31]: t.write('out.dat', format='ascii') In [32]: cat out.dat # 1 pxlname 1 # 2 x 0 ##pxlname x 1 1 In [33]: t2 = t.read('out.dat', fo...
2
2016-07-14T20:59:22Z
[ "python", "table", "header", "astropy" ]
Beginner recursion and list trouble going past second dimension
38,380,436
<p>I am trying to unembed a list recursively, but I am having trouble with an efficient way to do it past the second dimension. This works fine for the first two dimensions, but without going in depth with more if statements, it will not function past that. </p> <pre><code>UBLst = [] #Appends variables after they are ...
0
2016-07-14T17:19:35Z
38,381,739
<p>Sounds like you want to recursively flatten a list:</p> <pre><code>def flatten(myList): if isinstance(myList[0], list): out = [] for x in map(flatten, myList): out.extend(x) return out else: return myList </code></pre> <p>This technically should be safe for most common scenarios unless yo...
1
2016-07-14T18:34:44Z
[ "python", "list", "dimension" ]
Reverse all sub-matrices of a 3D matrix in NumPy
38,380,471
<p>I have a <code>3x5x5</code> "matrix" (actually a 3D <code>numpy.ndarray</code>). For the sake of some computation that I need to carry out, I must first reverse each subarray of this 3D array, as so: </p> <pre><code>&gt;&gt;&gt; x = np.arange(75).reshape(3, 5, 5) &gt;&gt;&gt; x array([[[ 0, 1, 2, 3, 4], ...
1
2016-07-14T17:22:02Z
38,380,507
<p>Just reverse along the <code>axes 1,2</code>, thus avoid the loop and hopefully gain some performance boost there. So, the desired output could be simply achieved like so -</p> <pre><code>x[:,::-1,::-1] </code></pre>
1
2016-07-14T17:24:22Z
[ "python", "arrays", "numpy", "matrix" ]
Django - 'module' object has no attribute 'site'
38,380,475
<p>When I try to runserver, it gives me this error. Any sample project is running without any issue.</p> <p><a href="http://i.stack.imgur.com/0xwrg.png" rel="nofollow">Trackback</a></p>
0
2016-07-14T17:22:35Z
38,380,937
<p>I've solved it.<br> Just did : "Invalidate caches/restart" and it worked fine.<br> Thanks to everyone who spared their valuable time.</p>
0
2016-07-14T17:49:18Z
[ "python", "django", "django-admin", "django-urls" ]
Feed Inception with OpenCV image
38,380,486
<p>Currently I'm feeding the test for Inception v3 with:</p> <pre><code>image_data = tf.gfile.FastGFile(image_path, 'rb').read() softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softmax_tensor, \ {'DecodeJpeg/contents:0': image_data}) </code></pre> <p>B...
1
2016-07-14T17:23:24Z
38,387,561
<p>Solved by using PIL instead of OpenCV. It is possible to feed it directly and also the drawing function seems better than the one I was using for OpenCV.</p> <pre><code>img = Image.open(tstImg) image = img.resize((1936, 1296), Image.ANTIALIAS) crop_img = image.crop((x, y, x+x_adds, y+y_adds)) predictions = sess.run...
0
2016-07-15T03:48:13Z
[ "python", "opencv", "neural-network", "tensorflow" ]
How would I print out any number x times as a list in python?
38,380,522
<p>If, for example, I want to print the number <code>5</code>, ten times...and then create a list from this, i.e.:</p> <pre><code>list = [5,5,5,5,5,5,5,5,5,5] </code></pre> <p>How would I achieve this?</p>
0
2016-07-14T17:25:34Z
38,380,552
<pre><code>In [39]: [5]*10 Out[39]: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] </code></pre>
4
2016-07-14T17:27:03Z
[ "python", "arrays", "list", "printing" ]
How would I print out any number x times as a list in python?
38,380,522
<p>If, for example, I want to print the number <code>5</code>, ten times...and then create a list from this, i.e.:</p> <pre><code>list = [5,5,5,5,5,5,5,5,5,5] </code></pre> <p>How would I achieve this?</p>
0
2016-07-14T17:25:34Z
38,382,362
<p>You can use the list multiplier (as the Vishnu Upadhyay answer) which will generate the whole list (take care with the <strong>memory</strong> when handling <strong>huge lists</strong>) :</p> <pre><code>[number] * times </code></pre> <p>Or you can use <em>itertools.repeat</em> to generate a generator:</p> <pre><c...
2
2016-07-14T19:08:17Z
[ "python", "arrays", "list", "printing" ]
How would I print out any number x times as a list in python?
38,380,522
<p>If, for example, I want to print the number <code>5</code>, ten times...and then create a list from this, i.e.:</p> <pre><code>list = [5,5,5,5,5,5,5,5,5,5] </code></pre> <p>How would I achieve this?</p>
0
2016-07-14T17:25:34Z
38,393,456
<pre><code>n = int(input()) list = [5]*n </code></pre> <p>maybe just add <code>try</code> in case someone entered non-integer</p>
0
2016-07-15T10:10:17Z
[ "python", "arrays", "list", "printing" ]
Accessing count column in PySpark
38,380,532
<pre><code>code: mydf = testDF.groupBy(testDF.word).count() mydf.show() output: +-----------+-----+ | word|count| +-----------+-----+ | she| 2208| | mothers| 93| | poet| 59| | moving| 18| | active| 6| | foot| 169| </code></pre> <p>I wanted to order this data frame based...
2
2016-07-14T17:26:01Z
38,380,696
<p>Well, dot notation is not the best method to access columns. While <code>DataFrame</code> provides column aware <code>__getattr__</code> you can encounter conflicts like this one, where name will resolve to a method (here <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame...
3
2016-07-14T17:35:52Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "pyspark-sql" ]
Why am I getting TypeError: an integer is required?
38,380,560
<p>This is my code snippet for where the traceback call shows an error:</p> <pre><code>def categorize(title): with conn: cur= conn.cursor() title_str= str(title) title_words= re.split('; |, |\*|\n',title_str) key_list= list(dictionary.keys()) flag2= 1 for word in title_words: ...
-2
2016-07-14T17:27:31Z
38,381,866
<p>map_letter_to_pos attempts to modify the global variable keyList without specifying it as a global variable, therefore it only modifies a local copy of keyList and then discards it. This causes next_val to have nothing to iterate, so it never reaches the if elif, and returns None.</p> <pre><code>end = None range(st...
0
2016-07-14T18:41:53Z
[ "python" ]
Checking user input to see if it satisfies two conditions
38,380,562
<p>As part of a larger menu-driven program, I'd like to test user input to see if that input: <em>is an integer</em> AND <em>if it is an integer, if it is within the range 1 to 12, inclusive</em>. </p> <pre><code>number = 0 while True: try: number = int(input("Enter a whole number between 1 and 12...
0
2016-07-14T17:27:40Z
38,380,681
<p>I don't think you need a whole <code>try</code>/<code>except</code> block. Everything can be fit into a single condition:</p> <pre><code>number = raw_input("Enter a whole number between 1 and 12 &gt;&gt;&gt; ") while not (number.isdigit() and type(eval(number)) == int and 1&lt;= eval(number) &lt;=12): number = ...
-1
2016-07-14T17:35:03Z
[ "python", "python-3.x", "try-except" ]
Checking user input to see if it satisfies two conditions
38,380,562
<p>As part of a larger menu-driven program, I'd like to test user input to see if that input: <em>is an integer</em> AND <em>if it is an integer, if it is within the range 1 to 12, inclusive</em>. </p> <pre><code>number = 0 while True: try: number = int(input("Enter a whole number between 1 and 12...
0
2016-07-14T17:27:40Z
38,380,699
<p>You don't need anything bar one <em>if</em> in the try:</p> <pre><code>while True: try: number = int(input("Enter a whole number between 1 and 12 &gt;&gt;&gt; ")) if 1 &lt;= number &lt;= 12: print("You selected:", number) break print("Need a whole number in range ...
1
2016-07-14T17:35:58Z
[ "python", "python-3.x", "try-except" ]
Checking user input to see if it satisfies two conditions
38,380,562
<p>As part of a larger menu-driven program, I'd like to test user input to see if that input: <em>is an integer</em> AND <em>if it is an integer, if it is within the range 1 to 12, inclusive</em>. </p> <pre><code>number = 0 while True: try: number = int(input("Enter a whole number between 1 and 12...
0
2016-07-14T17:27:40Z
38,380,712
<p>Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary <code>continue</code>s):</p> <pre><code>while True: try: number = int(input("Enter a whole number between 1 and 12 &gt;&gt;&gt; ")) except ValueError: print("Invalid input, please try again &gt;&gt;&gt; ") ...
0
2016-07-14T17:36:41Z
[ "python", "python-3.x", "try-except" ]
Checking user input to see if it satisfies two conditions
38,380,562
<p>As part of a larger menu-driven program, I'd like to test user input to see if that input: <em>is an integer</em> AND <em>if it is an integer, if it is within the range 1 to 12, inclusive</em>. </p> <pre><code>number = 0 while True: try: number = int(input("Enter a whole number between 1 and 12...
0
2016-07-14T17:27:40Z
38,380,812
<p>Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one <code>if</code> and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits. </p> <pre><code>while True: num_str = raw_input("Enter a whole number between 1 and 12 &gt...
0
2016-07-14T17:42:51Z
[ "python", "python-3.x", "try-except" ]
PyQt5 PushButton not showing
38,380,651
<p>This is the code I am using and the button doesn't show and it only shows a blank window. There is no error in the console.</p> <pre><code>from PyQt5 import QtWidgets from PyQt5.QtWidgets import * import sys def start(): app = QApplication(sys.argv) w = QWidget() w.resize(128,102) w.move(0, 0) ...
0
2016-07-14T17:32:52Z
38,380,707
<p>Try passing the parent argument to the constructor. The parent argument causes the button to be owned by Qt, not PyQt. <code>btn = QtWidgets.QPushButton("Hi", w)</code> should work.</p>
2
2016-07-14T17:36:26Z
[ "python", "pyqt", "pyqt5" ]
PyQt5 PushButton not showing
38,380,651
<p>This is the code I am using and the button doesn't show and it only shows a blank window. There is no error in the console.</p> <pre><code>from PyQt5 import QtWidgets from PyQt5.QtWidgets import * import sys def start(): app = QApplication(sys.argv) w = QWidget() w.resize(128,102) w.move(0, 0) ...
0
2016-07-14T17:32:52Z
38,398,329
<p>Any widget you want to be shown needs to be parented, either directly or indirectly, to the widget you want it to appear in. </p> <p>The common way to do this is by assigning your widget a layout and adding other widgets or sublayouts to it.</p> <pre><code>widget = QtWidgets.QWidget() button = QtWidgets.QPushButto...
0
2016-07-15T14:14:19Z
[ "python", "pyqt", "pyqt5" ]
PyQt5 PushButton not showing
38,380,651
<p>This is the code I am using and the button doesn't show and it only shows a blank window. There is no error in the console.</p> <pre><code>from PyQt5 import QtWidgets from PyQt5.QtWidgets import * import sys def start(): app = QApplication(sys.argv) w = QWidget() w.resize(128,102) w.move(0, 0) ...
0
2016-07-14T17:32:52Z
38,409,113
<pre><code>from PyQt5 import QtWidgets from PyQt5.QtWidgets import * import sys def start(): app = QApplication(sys.argv) w = QWidget() w.resize(128,102) w.move(0, 0) w.setWindowTitle('Simple') btn = QtWidgets.QPushButton (w) btn.move(50, 50) btn.resize(btn.sizeHint()) ...
0
2016-07-16T08:00:18Z
[ "python", "pyqt", "pyqt5" ]
How can I traverse a deeply nested dictionary which has lists and other dictionaries within it in Python?
38,380,678
<p>I'm fairly new to Python and I am trying to build up filter query as my final result with a dictionary with n-depth. Inside it could other dictionaries and lists.</p> <p>This is my structure:</p> <pre><code>filters = { predicate: 'AND', filters: [ {'property_class_id': 10, operator: 'contains', operan...
1
2016-07-14T17:34:44Z
38,380,955
<p>I've changed the structure a tiny bit to make it run. You can simply integrate the modified <code>unpack_filter</code> loop into your code:</p> <pre><code>base_filter = { 'predicate': 'AND', 'filters': [ {'property_class_id': 10, 'operator': 'contains', 'operands': ['FOO']}, { 'predicate': 'NOT', ...
0
2016-07-14T17:50:29Z
[ "python", "django", "list", "dictionary", "recursion" ]
How can I traverse a deeply nested dictionary which has lists and other dictionaries within it in Python?
38,380,678
<p>I'm fairly new to Python and I am trying to build up filter query as my final result with a dictionary with n-depth. Inside it could other dictionaries and lists.</p> <p>This is my structure:</p> <pre><code>filters = { predicate: 'AND', filters: [ {'property_class_id': 10, operator: 'contains', operan...
1
2016-07-14T17:34:44Z
38,382,008
<p>As stated in the previous answer you can use the 'in' operator to loop through either keys in a dictionary or items in a list. This way you can have one loop with if statements that decide how to respond. The above answer will print the keys and values of the innermost dictionaries, which might be what you want. He...
0
2016-07-14T18:48:46Z
[ "python", "django", "list", "dictionary", "recursion" ]
DoesNotExist at /accounts/register/ Site matching query does not exist. (django, python)
38,380,691
<p>Trying again to implement django-registration. When I try to deploy it to the heroku and to register a new user, it gives me a strange error:</p> <pre><code>Traceback: #some irrelevant traceback File "/app/.heroku/python/lib/python2.7/site-packages/registration/views.py" in post 43. return self.form...
1
2016-07-14T17:35:42Z
38,380,813
<p>If you have <code>django.contrib.sites</code> in your <code>INSTALLED_APPS</code> and you are not having multiple sites, then you have remove it and do a round of <code>makemigration</code> and <code>migrate</code>.</p> <p>In case you have multiple sites, then ref: <a href="http://stackoverflow.com/questions/160685...
0
2016-07-14T17:43:02Z
[ "python", "django", "heroku", "django-registration" ]
pandas read_json: "If using all scalar values, you must pass an index"
38,380,795
<p>I have some difficulty in importing a JSON file with pandas.</p> <pre><code>import pandas as pd map_index_to_word = pd.read_json('people_wiki_map_index_to_word.json') </code></pre> <p>This is the error that I get: </p> <pre><code>ValueError: If using all scalar values, you must pass an index </code></pre> <p>Th...
0
2016-07-14T17:41:10Z
38,381,219
<p>Try</p> <pre><code>ser = pd.read_json('people_wiki_map_index_to_word.json', typ='series') </code></pre> <p>That file only contains key value pairs where values are scalars. You can convert it to a dataframe with <code>ser.to_frame('count')</code>.</p> <p>You can also do something like this:</p> <pre><code>import...
0
2016-07-14T18:05:30Z
[ "python", "pandas" ]
Python code to select/change photo region color & pattern
38,380,799
<p>I am looking for some guidance on how to to write a piece of code (python preferred) to change the color/pattern of the counte top on this picture to something else the user will choose.I am looking into Python PIL right now but can't find a way to select/paste new pattern into the picture. Any help much appreciated...
0
2016-07-14T17:41:30Z
38,381,815
<p>You will need to use the <code>Image</code> module to do what it is you are trying to accomplish. </p> <pre><code>import Image picture = Image.open("/path/of/your/picture.jpg") # Get the dimensions of your picture width, height = picture.size() # Process the pixels you are focused on for x in width: for y in ...
0
2016-07-14T18:38:56Z
[ "python" ]
Loop Counting Scoping In Python
38,380,819
<p>I'm trying to figure out how this code works. How is <code>i</code> accessible outside the for loop?</p> <pre><code># Palindrome of string str=raw_input("Enter the string\n") ln=len(str) for i in range(ln/2) : if(str[ln-i-1]!=str[i]): break if(i==(ln/2)-1): ## How is i accessible outside the for...
5
2016-07-14T17:43:17Z
38,380,909
<p>This is part of Python. Variables declared inside for loops (that includes loop counters) won't decay until they fully leave scope.</p> <p>Take a look at this question:</p> <p><a href="http://stackoverflow.com/questions/3611760/scoping-in-python-for-loops">Scoping In Python For Loops</a></p> <p>From the answers:<...
1
2016-07-14T17:48:03Z
[ "python", "scope", "palindrome" ]
Python3.5 function that calls object's method returns None instead of object
38,380,936
<p>I have a class and a function that tries to update and return instances of this class:</p> <pre><code>class Foo: def __init__(self): self.datum = 'a' def update(self): self.datum = 'b' if self.datum == 'a' else 'a' def updater(foo_obj): return( foo_obj.update() ) </code></pre> <p>but c...
-1
2016-07-14T17:49:11Z
38,380,979
<p>Your <code>update</code> method does not return anything, which in Python means that it implicitly returns <code>None</code>. If you want it to have a meaningful return value, you'd have to do so explicitly. E.g.:</p> <pre><code>def update(self): self.datum = 'b' if self.datum == 'a' else 'a' return self.da...
1
2016-07-14T17:51:34Z
[ "python", "python-3.x", "return" ]
Python3.5 function that calls object's method returns None instead of object
38,380,936
<p>I have a class and a function that tries to update and return instances of this class:</p> <pre><code>class Foo: def __init__(self): self.datum = 'a' def update(self): self.datum = 'b' if self.datum == 'a' else 'a' def updater(foo_obj): return( foo_obj.update() ) </code></pre> <p>but c...
-1
2016-07-14T17:49:11Z
38,381,007
<p>Update method updater.</p> <pre><code>def updater(foo_obj): foo_obj.update() return( foo_obj ) </code></pre> <p>OR <code>return self</code> from class function:</p> <pre><code>def update(self): self.datum = 'b' if self.datum == 'a' else 'a' return self </code></pre>
1
2016-07-14T17:53:19Z
[ "python", "python-3.x", "return" ]
Python3.5 function that calls object's method returns None instead of object
38,380,936
<p>I have a class and a function that tries to update and return instances of this class:</p> <pre><code>class Foo: def __init__(self): self.datum = 'a' def update(self): self.datum = 'b' if self.datum == 'a' else 'a' def updater(foo_obj): return( foo_obj.update() ) </code></pre> <p>but c...
-1
2016-07-14T17:49:11Z
38,381,025
<p>If you'd like <code>update</code> to return instances of the <code>Foo</code> class, you have to explicitly have it do so with a return statement, otherwise it will implicitly return <code>None</code> (i.e. it's a void method, even though Python doesn't use these terms because duck-typing). Do this like so:</p> <pr...
0
2016-07-14T17:54:34Z
[ "python", "python-3.x", "return" ]
use time series data in python to calculate mean, variance std deviation
38,380,945
<p>I have data collected from sensors that looks like: </p> <pre><code>sec nanosec value 1001 1 0.2 1001 2 0.2 1001 3 0.2 1002 1 0.1 1002 2 0.2 1002 3 0.1 1003 1 0.2 1003 2 0.2 1003 3 0.1 1004 1 0.2 1004 2 ...
3
2016-07-14T17:49:46Z
38,382,157
<p>I think you can first convert column <code>sec</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</...
2
2016-07-14T18:56:37Z
[ "python", "pandas", "time-series" ]
use time series data in python to calculate mean, variance std deviation
38,380,945
<p>I have data collected from sensors that looks like: </p> <pre><code>sec nanosec value 1001 1 0.2 1001 2 0.2 1001 3 0.2 1002 1 0.1 1002 2 0.2 1002 3 0.1 1003 1 0.2 1003 2 0.2 1003 3 0.1 1004 1 0.2 1004 2 ...
3
2016-07-14T17:49:46Z
38,382,456
<p>Borrowing jezrael's code to setup things up:</p> <pre><code>df['sec'] = pd.to_timedelta(df.sec, unit='s') df.set_index('sec', inplace=True) print (df) nanosec value sec 00:16:41 1 0.2 00:16:41 2 0.2 00:16:41 3 0.2 00:16:42 1 0.1 00:16:42 ...
2
2016-07-14T19:14:43Z
[ "python", "pandas", "time-series" ]
Running asynchronous queries in BigQuery not noticeably faster
38,380,957
<p>I am using Google's python API client library on App Engine to run a number of queries in Big Query to generate live analytics. The calls take roughly two seconds each and with five queries, this is too long, so I looked into ways to speed things up and thought <a href="https://cloud.google.com/bigquery/querying-dat...
1
2016-07-14T17:50:37Z
38,383,990
<p>The answer to whether running queries in parallel will speed up the results is, of course, "it depends".</p> <p>When you use the asynchronous job API there is about a half a second of built-in latency that gets added to every query. This is because the API is not designed for short-running queries; if your queries ...
2
2016-07-14T20:48:18Z
[ "python", "google-app-engine", "asynchronous", "google-bigquery", "google-api-python-client" ]
Change a year in pandas dataframe if it is lower than 1900
38,381,031
<p>I have to process data where someone has been using a date value with a year of 1700 where there is not an actual event date. 1700 breaks datetime, which starts at 1900, but I'm sure you all know that.</p> <p>I have converted the data to datetime and then tried an if statement:</p> <pre><code>df["DATE"] = pd.to_da...
1
2016-07-14T17:55:09Z
38,381,249
<p>Im having trouble reproducing this issue exactly, but have you tried:</p> <pre><code>df[df.DATE.dt.year &lt; 1900] = dt.datetime.today() df.DATE = df.DATE.map(lambda x: x.strftime("%m/%d/%y")) </code></pre>
2
2016-07-14T18:07:13Z
[ "python", "datetime", "pandas" ]
pandas complicated join operation
38,381,072
<p>I would like to implement a specific join operation with the following requirements:</p> <p>I have a data frame in the following format, where the index is datetime and I have columns from 0 to N (9 in this example)</p> <p>df1:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 2001-01-01 2 53 ...
2
2016-07-14T17:57:22Z
38,381,242
<p>Something along these lines taken from NumPy's indexing methods -</p> <pre><code>vals = df1.values[np.arange(df1.shape[0]),df2[0].values] df_out = pd.DataFrame(vals,index=df1.index) </code></pre>
3
2016-07-14T18:06:33Z
[ "python", "pandas", "join", "merge" ]
pandas complicated join operation
38,381,072
<p>I would like to implement a specific join operation with the following requirements:</p> <p>I have a data frame in the following format, where the index is datetime and I have columns from 0 to N (9 in this example)</p> <p>df1:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 2001-01-01 2 53 ...
2
2016-07-14T17:57:22Z
38,381,542
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow"><code>lookup</code></a>:</p> <pre><code>print (df1.lookup(df1.index, df2.iloc[:,0])) [68 7 46] print (pd.DataFrame(df1.lookup(df1.index, df2.iloc[:,0]), index=df1.index)) 0 2001-01-...
3
2016-07-14T18:24:25Z
[ "python", "pandas", "join", "merge" ]
Python3 insertion sort iterating backwards not working
38,381,119
<p>I'm a beginner in Python and am trying to implement insertion sort in the language. However, when I try my code on a list to sort I get the same list back. I figured out that the code isn't even going to the second loop. I am using Python 3. What is wrong with iterating backwards this way?</p> <pre><code>def ins_so...
1
2016-07-14T17:59:58Z
38,381,550
<p>You have 2 issues in your code right now. Mouse over the yellow if you can't figure it out ;)</p> <p>One is in this piece of code:</p> <pre><code>for key in range(1, len(us_in)-1): </code></pre> <blockquote class="spoiler"> <p>You want to do <code>for key in range(1, len(us_in)):</code> so you reach every eleme...
1
2016-07-14T18:24:43Z
[ "python", "python-3.x", "insertion-sort" ]
Python3 insertion sort iterating backwards not working
38,381,119
<p>I'm a beginner in Python and am trying to implement insertion sort in the language. However, when I try my code on a list to sort I get the same list back. I figured out that the code isn't even going to the second loop. I am using Python 3. What is wrong with iterating backwards this way?</p> <pre><code>def ins_so...
1
2016-07-14T17:59:58Z
38,381,552
<p>Tip: Put "prints" everywhere, these will help you following the state of your variables.</p> <p>That said, try putting the tmp variable outside the "if" statement. And for running backwards, try this:</p> <pre><code> for i in range(end): backwards = end - i #do something using "backwards" instead of...
0
2016-07-14T18:24:54Z
[ "python", "python-3.x", "insertion-sort" ]
Python3 insertion sort iterating backwards not working
38,381,119
<p>I'm a beginner in Python and am trying to implement insertion sort in the language. However, when I try my code on a list to sort I get the same list back. I figured out that the code isn't even going to the second loop. I am using Python 3. What is wrong with iterating backwards this way?</p> <pre><code>def ins_so...
1
2016-07-14T17:59:58Z
38,382,394
<p>There are mainly 2 lines that you need to edit. 3rd line it should be len (us_in) not len(us_in)-1 And in the if statement it should be i >= 0 Instead of Key !=0 Also the second loop should start backward from key -1{ one less iteration} </p>
0
2016-07-14T19:10:07Z
[ "python", "python-3.x", "insertion-sort" ]
How to sample data by keeping at least two non zero columns
38,381,345
<p>I have a pandas data frame which is basically 50K X9.5K dimensions. My dataset is binary that is it has 1 and 0 only. And has lot of zeros. </p> <p>Think of it as a user-item purchase data where its 1 if user purchased an item else 0. Users are rows and items are columns. </p> <pre><code>353 0 0 0 0 0 0 ...
2
2016-07-14T18:12:59Z
38,381,638
<p>So, by non-zero, I am guessing you mean those columns which only have ones in them. That is fairly easy to do. Best approach probably is to use sum, like so:</p> <pre><code>sums = df.sum(axis=1) # to sum along columns. You will have a Series with column names as indices, and column sums as values. non_zero_cols = s...
1
2016-07-14T18:29:48Z
[ "python", "numpy", "pandas" ]
How to sample data by keeping at least two non zero columns
38,381,345
<p>I have a pandas data frame which is basically 50K X9.5K dimensions. My dataset is binary that is it has 1 and 0 only. And has lot of zeros. </p> <p>Think of it as a user-item purchase data where its 1 if user purchased an item else 0. Users are rows and items are columns. </p> <pre><code>353 0 0 0 0 0 0 ...
2
2016-07-14T18:12:59Z
38,381,713
<p>IIUC:</p> <pre><code>threshold = 6 new_df = df.loc[df.sum(1) &gt;= threshold] </code></pre> <p><code>df.sum(1)</code> sums over each row. Since these are <code>1</code>s and <code>0</code>s, this is equivalent to counting.</p> <p><code>df.sum(1) &gt;= threshold</code> creates series of <code>True</code>s and <co...
1
2016-07-14T18:33:21Z
[ "python", "numpy", "pandas" ]
How to create multiple complex sqlite transactions with an expected out using apsw?
38,381,356
<p>I want to execute several complex statements in a transaction with a select statement at the end which I use for further processing.</p> <p>Doing so once works fine but as soon as I execute the same statement again it causes the error below.</p> <p>Test code:</p> <pre><code>import apsw connection = apsw.Connectio...
1
2016-07-14T18:13:39Z
38,383,740
<p>SQLite computes results on the fly. When you call <code>fetchone()</code>, the execution runs only as far as needed to return one row.</p> <p>To ensure that all statements are executed, call <code>fetchall()</code>, or iterate over the results, even if you know that there is only one.</p> <p>It might be a better i...
0
2016-07-14T20:30:29Z
[ "python", "sqlite", "transactions" ]
Putting values into SQL Server Database Table using PYMSSQL
38,381,391
<p>I am trying to put values into the Table of a Database on SQL Server.</p> <p>My program will subscribe to an MQTT Server and whenever it receives a message, it will put the message into the table of the database.</p> <p>The following is my code:</p> <pre><code>import paho.mqtt.client as mqtt import signal import ...
0
2016-07-14T18:15:42Z
38,381,543
<ol> <li><p>You should post your error as text directly in your question.</p></li> <li><p>The error clearly suggests that the <code>query_params</code> argument should be a<br> tuple or a dictionary and not a list.</p> <pre><code>cursor.execute("INSERT INTO Topic VALUES (%d)", [(id, deviceID, time)]) </...
0
2016-07-14T18:24:26Z
[ "python", "mqtt", "pymssql" ]
Error in py.test in pycharm
38,381,432
<p>When i run pytest on my system, it gives an error: no tests ran in 0.01 seconds . Can someone tell me if its because of error in my code or some other reason.</p> <p>Output is : </p> <pre><code>============================= test session starts ============================== platform darwin -- Python 2.7.11, pytest...
-2
2016-07-14T18:18:18Z
38,477,976
<p>I also had the same issue, the fix is to change the rootdir.</p> <p>Go to <code>Setting-&gt;tools-&gt;externaltools</code> and set the parameters as <code>"$FileName$"</code> and working directory as <code>"$FileDir$"</code> for your pyTest</p> <p><a href="http://i.stack.imgur.com/atdqM.jpg" rel="nofollow"><img sr...
0
2016-07-20T09:54:17Z
[ "python", "pycharm", "py.test" ]
How do I filter incoming data from a socket in Python?
38,381,540
<p>I am using a UDP socket program for one of my projects to read in incoming data from an EEG headset. I then use this data to control servo motors in a robotic arm. The code that I am using to create the socket and print out the data works fine.</p> <pre><code>import socket import subprocess UDP_IP = "169.254.110.1...
1
2016-07-14T18:24:21Z
38,382,378
<p>This might help.</p> <p><strong>Server</strong></p> <pre><code>import socket s = socket.socket() UDP_IP = "169.254.110.133" UDP_PORT = 50000 sock.bind((UDP_IP, UDP_PORT)) s.listen(5) while True: c, addr = s.accept() c.send('Connected to ser...
0
2016-07-14T19:09:06Z
[ "python", "sockets", "udp" ]
Is it pythonic: naming lambdas
38,381,556
<p>I'm beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, <code>map</code>, <a href="http://stackoverflow.com/a/16509/1533474">functions returning functions</a>, etc. However, I've also been naming lambdas within functions because:</p> <ul> <li>I ne...
3
2016-07-14T18:25:17Z
38,381,606
<p>These are functionally (no pun intended) identical.</p> <pre><code>indexer = lambda a0, a1, idx: a0[idx] + a1[idx] def indexer(a0, a1, idx): return a0[idx] + a1[idx] </code></pre> <p>If you have an aesthetic preference for one or the other, then use it.</p>
0
2016-07-14T18:28:09Z
[ "python", "lambda" ]
Is it pythonic: naming lambdas
38,381,556
<p>I'm beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, <code>map</code>, <a href="http://stackoverflow.com/a/16509/1533474">functions returning functions</a>, etc. However, I've also been naming lambdas within functions because:</p> <ul> <li>I ne...
3
2016-07-14T18:25:17Z
38,381,652
<blockquote> <p>I've written a named lambda expression to do the indexing instead of writing a whole other function</p> </blockquote> <p>Well, you <em>are</em> writing a whole other function. You're just writing it with a lambda expression.</p> <p>Why not use <code>def</code>? You get nicer stack traces and more sy...
3
2016-07-14T18:30:31Z
[ "python", "lambda" ]
Is it pythonic: naming lambdas
38,381,556
<p>I'm beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, <code>map</code>, <a href="http://stackoverflow.com/a/16509/1533474">functions returning functions</a>, etc. However, I've also been naming lambdas within functions because:</p> <ul> <li>I ne...
3
2016-07-14T18:25:17Z
38,381,663
<p>This is not Pythonic and <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations">PEP8 discourages it</a>:</p> <blockquote> <p>Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.</p> <p>Yes:</p> <pre><code>def f(x):...
6
2016-07-14T18:31:00Z
[ "python", "lambda" ]
Python unittest and mock: Check if a function gets called, but then stop the test
38,381,602
<p>Let's say I want to make sure that certain flags etc get dispatched properly so that deep within my library, a particular function gets called:</p> <p><code>high_order_function_call(**kwargs)</code> deep down contains <code>library_function_call()</code> and I want to make sure that it gets actually called.</p> <p...
1
2016-07-14T18:28:02Z
38,382,212
<p>You could try using an exception raising side effect on the call, and then catch that exception in your test.</p> <pre><code>from mock import Mock, patch import os.path class CallException(Exception): pass m = Mock(side_effect=CallException('Function called!')) def caller_test(): os.path.curdir() rais...
1
2016-07-14T18:59:36Z
[ "python", "unit-testing", "mocking" ]
Elastic cloud - unable to create index
38,381,617
<p>I am trying to use elastic cloud hosted elasticsearch service <a href="https://www.elastic.co/cloud" rel="nofollow">https://www.elastic.co/cloud</a> </p> <p>I am using python and elasticsearch-py package to connect in my flaks app:</p> <pre><code>es_connection = Elasticsearch( ["https://myuser:mysecret@xxxxxxx....
1
2016-07-14T18:28:51Z
38,406,876
<p>I fixed it by putting both usernames in the same line. Like this:</p> <p><code>admin: admin, myuser</code></p>
0
2016-07-16T01:27:25Z
[ "python", "elasticsearch", "elasticsearch-2.0" ]
How to read text file on python and get values from it to set it on an array
38,381,649
<p>I have a text file which have the following structure:</p> <p>&lt; example_name>TAB&lt; probability >TAB&lt; prediction></p> <p>This an example of this file: </p> <blockquote> <p>Q1_R1 0.00390625 true</p> <p>Q1_R2 0.0078125 false</p> <p>Q1_R3 0.001953125 false</p> <p>Q1_R4 0.125 true</p> </b...
-1
2016-07-14T18:30:23Z
38,381,855
<p>Please, make an attempt before you ask a question. In Python, the way I would do that would be to use a <strong>list comprehension</strong> when reading the file</p> <pre><code>probs = [line.split()[1] for line in open('filename','r')] </code></pre>
2
2016-07-14T18:41:15Z
[ "python", "arrays", "scikit-learn" ]
Efficiently comparing the first item in each list of two large list of lists?
38,381,755
<p>I'm currently working with a a large list of lists (~280k lists) and a smaller one (~3.5k lists). I'm trying to efficiently compare the first index in the smaller list to the first index in the large list. If they match, I want to return both lists from the small and large list that have a matching first index.</p> ...
1
2016-07-14T18:35:35Z
38,382,015
<p>I'm actually using Python 2.7.11, although I guess this may work.</p> <pre><code>l1 =[['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],['m','n','o','p']] l2 =[['e','q','r','s'],['a','t','w','s']] def org(Smalllist,Largelist): L = Largelist S = Smalllist Final = [] for i in range(len(S)): ...
-1
2016-07-14T18:49:00Z
[ "python", "list", "python-3.x" ]
Efficiently comparing the first item in each list of two large list of lists?
38,381,755
<p>I'm currently working with a a large list of lists (~280k lists) and a smaller one (~3.5k lists). I'm trying to efficiently compare the first index in the smaller list to the first index in the large list. If they match, I want to return both lists from the small and large list that have a matching first index.</p> ...
1
2016-07-14T18:35:35Z
38,382,063
<p>Assuming order doesn't matter, I would highly recommend using a dictionary to map prefix (one character) to items and <code>set</code> to find matches:</p> <pre><code># generation of data... not important &gt;&gt;&gt; lst1 = [list(c) for c in ["abcd", "efgh", "ijkl", "mnop"]] &gt;&gt;&gt; lst2 = [list(c) for c in [...
4
2016-07-14T18:51:19Z
[ "python", "list", "python-3.x" ]
Efficiently comparing the first item in each list of two large list of lists?
38,381,755
<p>I'm currently working with a a large list of lists (~280k lists) and a smaller one (~3.5k lists). I'm trying to efficiently compare the first index in the smaller list to the first index in the large list. If they match, I want to return both lists from the small and large list that have a matching first index.</p> ...
1
2016-07-14T18:35:35Z
38,382,292
<p>Here's a one liner using list comprehension. I'm not sure how efficient it is, though.</p> <pre><code>large = [list(c) for c in ["abcd", "efgh", "ijkl", "mnop"]] small = [list(c) for c in ["eqrs", "atws"]] ret = [(x,y) for x in large for y in small if x[0] == y[0]] print ret #output [(['a', 'b', 'c', 'd'], ['a', '...
0
2016-07-14T19:04:54Z
[ "python", "list", "python-3.x" ]
Monkeypatching input causes attribute error during testing
38,381,763
<p>I'm trying to monkeypatch in pytest the input function to simulate user input but I'm getting an attribute error.</p> <p>I receive the same error when I use the mock.patch.object as well. But I'm able to readily monkeypatch the input when I'm in a regular Python environment, I only get this error in testing.<a href...
0
2016-07-14T18:36:09Z
38,381,835
<p><code>__builtins__</code> is an implementation detail. You shouldn't touch it. What you're looking for is either the <code>__builtin__</code> (no <code>s</code>) or <code>builtins</code> module, depending on whether you're on Python 2 or 3.</p> <p>Judging by the details of the error you got, you're on Python 3, so ...
3
2016-07-14T18:40:02Z
[ "python", "python-3.x", "py.test" ]
convert charfield to string django
38,381,803
<p>I am trying to convert a CharField to a string in Django 1.2.5</p> <p>I have this in my template:</p> <pre><code>{% mp3_metadata audio.audiogalleryitem.link %} </code></pre> <p>and a custom template tag:</p> <pre><code>@register.simple_tag def mp3_metadata(link): link = str(link) filename, headers = urll...
-1
2016-07-14T18:38:29Z
38,395,235
<p>Actually it appeared to be a wav file in the mp3 playlist causing the error, it was just difficult to track down.</p>
0
2016-07-15T11:40:54Z
[ "python", "django", "string", "templates", "type-conversion" ]
How to check whether for loop ends completely in python?
38,381,850
<p>This is a ceased for loop :</p> <pre><code>for i in [1,2,3]: print(i) if i==3: break </code></pre> <p>How can I check its difference with this : </p> <pre><code>for i in [1,2,3]: print(i) </code></pre> <p>This is an idea :</p> <pre><code>IsBroken=False for i in [1,2,3]: print(i) if i...
3
2016-07-14T18:40:49Z
38,381,893
<p><code>for</code> loops can take an <code>else</code> block which can serve this purpose:</p> <pre><code>for i in [1,2,3]: print(i) if i==3: break else: print("for loop was not broken") </code></pre>
10
2016-07-14T18:43:15Z
[ "python", "loops", "for-loop", "break" ]
How to check whether for loop ends completely in python?
38,381,850
<p>This is a ceased for loop :</p> <pre><code>for i in [1,2,3]: print(i) if i==3: break </code></pre> <p>How can I check its difference with this : </p> <pre><code>for i in [1,2,3]: print(i) </code></pre> <p>This is an idea :</p> <pre><code>IsBroken=False for i in [1,2,3]: print(i) if i...
3
2016-07-14T18:40:49Z
38,381,903
<p>Python <code>for</code> loop has a else clause that is called iff the loop ends.</p> <p>So, this would mean something in line</p> <pre><code>for i in [1,2,3]: print(i) if i==3: break else: print("Loop Ended without break") </code></pre> <p>If instead you need to handle both the scenario, using...
2
2016-07-14T18:43:39Z
[ "python", "loops", "for-loop", "break" ]
Python 2.6: encode() takes no keyword arguments
38,381,853
<p>Hopefully simple question here, I have a value that based on if its unicode, must be encoded. I use the built in string.encode class</p> <p>code is simple:</p> <pre><code>if value_t is unicode: values += (value.encode('utf-8', errors='backslashreplace'), None) continue </code></pre>...
1
2016-07-14T18:41:02Z
38,381,924
<p>The Python docs for <a href="https://docs.python.org/2.7/library/stdtypes.html#str.encode" rel="nofollow">encode</a> explain why you're seeing this issue. Specifically: <code>Changed in version 2.7: Support for keyword arguments added</code></p>
3
2016-07-14T18:44:43Z
[ "python" ]
Python 2.6: encode() takes no keyword arguments
38,381,853
<p>Hopefully simple question here, I have a value that based on if its unicode, must be encoded. I use the built in string.encode class</p> <p>code is simple:</p> <pre><code>if value_t is unicode: values += (value.encode('utf-8', errors='backslashreplace'), None) continue </code></pre>...
1
2016-07-14T18:41:02Z
38,382,375
<p>Since method signatures tend to change from version to version, You should always read the relevant documentation to version you are working with</p> <p>From <a href="https://docs.python.org/2.6/library/stdtypes.html#str.encode" rel="nofollow">str.encode</a> documentation for python 2.6, the method signature is:</p...
0
2016-07-14T19:09:00Z
[ "python" ]
How to read json files in Tensorflow?
38,381,887
<p>I'm trying to write a function, that reads json files in tensorflow. The json files have the following structure: </p> <pre><code>{ "bounding_box": { "y": 98.5, "x": 94.0, "height": 197, "width": 188 }, "rotation": { "yaw": -27.97019577026367, "roll":...
3
2016-07-14T18:42:54Z
38,384,237
<p>This might be skirting the issue, but you could preprocess your data with a command line tool like <a href="https://stedolan.github.io/jq/tutorial/" rel="nofollow">https://stedolan.github.io/jq/tutorial/</a> into a line-based data format, like csv. Would possibly be more efficient also.</p>
0
2016-07-14T21:05:01Z
[ "python", "json", "neural-network", "tensorflow" ]
How to read json files in Tensorflow?
38,381,887
<p>I'm trying to write a function, that reads json files in tensorflow. The json files have the following structure: </p> <pre><code>{ "bounding_box": { "y": 98.5, "x": 94.0, "height": 197, "width": 188 }, "rotation": { "yaw": -27.97019577026367, "roll":...
3
2016-07-14T18:42:54Z
39,610,791
<p>You can use standard python json parsing with TensorFlow if you wrap the functions with <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/script_ops.html" rel="nofollow"><code>tf.py_func</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import json import numpy as np import tensorflow ...
0
2016-09-21T08:04:22Z
[ "python", "json", "neural-network", "tensorflow" ]
MultipleChoiceField - invalid_choice error - Select a valid choice. SomeChoice is not one of the available choices
38,381,994
<p>I am creating a form in django, hoping to allow users to delete some of their devices. When I click on the submit button of my form, I keep getting the message: <code>Select a valid choice. &lt;Some choice&gt; is not one of the available choices</code>. Here is my code. Thanks a lot :)</p> <h1>forms.py</h1> <pre><...
1
2016-07-14T18:48:12Z
38,383,607
<p>You've set the list of valid choices on the GET request only. On the POST, there are no choices, so the field can never be valid.</p> <p>That code should go in the form's <code>__init__</code> method, so it is run every time the form is instantiated.</p>
1
2016-07-14T20:21:57Z
[ "python", "django", "forms", "multiplechoicefield" ]
MultipleChoiceField - invalid_choice error - Select a valid choice. SomeChoice is not one of the available choices
38,381,994
<p>I am creating a form in django, hoping to allow users to delete some of their devices. When I click on the submit button of my form, I keep getting the message: <code>Select a valid choice. &lt;Some choice&gt; is not one of the available choices</code>. Here is my code. Thanks a lot :)</p> <h1>forms.py</h1> <pre><...
1
2016-07-14T18:48:12Z
38,384,756
<p>Thanks to @Daniel Roseman, I was able to figure it out. </p> <p>Here is how I changed my code : </p> <h1>forms.py</h1> <pre><code>class DeleteDeviceForm(forms.Form): devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,label="Select the devices you want to delete:") def __init__(self, ...
0
2016-07-14T21:44:37Z
[ "python", "django", "forms", "multiplechoicefield" ]
Ignore Lock in MYSQL Database in Sqlalchemy Query
38,382,028
<p>Using SQLAlchemy to query a MySQL database I am getting the following error: </p> <blockquote> <p><code>sqlalchemy.exc.OperationalError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (_mysql_exceptions.OperationalError) (1205, '...
8
2016-07-14T18:49:41Z
38,446,073
<p>Assuming you are using the <a href="http://dev.mysql.com/downloads/connector/python/" rel="nofollow">mysql.connector</a>, the default value of the <code>autocommit</code> Property is False, which might cause your script to hang due to other session that is waiting to finish.</p> <p><code>SQLAlchemy</code> is using ...
1
2016-07-18T21:12:49Z
[ "python", "mysql", "session", "sqlalchemy", "locking" ]
Random Sample From Probability Distribution a certain number of times
38,382,075
<p>Let's say I have a normal distribution, and I want to sample from it 1000 times and if the value is in the top 20th percentile, I want to add 1 to a counter. What's the optimal solution for this?</p> <p>I'm trying to solve this using numpy and can't figure out the math behind it. Right now I have this but I feel ...
2
2016-07-14T18:51:52Z
38,382,213
<p>If you have a normal distribution, I'll assume you know <code>mu</code> and <code>sigma</code>, otherwise this question requires some extra post-processing. You'll have a certain <code>Z=(X-mu)/sigma</code> for each element you take out. Your 20th percentile would be any <code>X</code> that makes <code>Z&gt;0.842</c...
1
2016-07-14T18:59:39Z
[ "python", "numpy", "math" ]
Random Sample From Probability Distribution a certain number of times
38,382,075
<p>Let's say I have a normal distribution, and I want to sample from it 1000 times and if the value is in the top 20th percentile, I want to add 1 to a counter. What's the optimal solution for this?</p> <p>I'm trying to solve this using numpy and can't figure out the math behind it. Right now I have this but I feel ...
2
2016-07-14T18:51:52Z
38,382,367
<p>This is the generated array (you can play with mean and standard deviation, they are the default ones):</p> <pre><code>mu = 0 std = 1 arr = np.random.normal(mu, std, 1000) </code></pre> <p>This gives you the number of items in the top 20 percentile:</p> <pre><code>arr[arr &gt; np.percentile(arr, 80)].size Out[30]...
1
2016-07-14T19:08:34Z
[ "python", "numpy", "math" ]
New object instance every call
38,382,142
<p><strong>DJANGO APP</strong></p> <p>I have interface for sending e-mail in Django:</p> <pre><code>from my_app.utils import com com.mail.email_category1(subject, template, ...) ... com.mail.email_category2(subject, template, ...) </code></pre> <p>I have also another interafces for ie. for SMS:</p> <pre><code>com....
0
2016-07-14T18:55:54Z
38,385,980
<p>Python modules are singleton, so it will only import it once, so <code>mail = CommunicationMail()</code> is executed once.</p> <p>you can:</p> <pre><code>from my_app.utils import com com.CommunicationSms().sms_category1(template, ...) </code></pre>
0
2016-07-15T00:01:27Z
[ "python", "django" ]
New object instance every call
38,382,142
<p><strong>DJANGO APP</strong></p> <p>I have interface for sending e-mail in Django:</p> <pre><code>from my_app.utils import com com.mail.email_category1(subject, template, ...) ... com.mail.email_category2(subject, template, ...) </code></pre> <p>I have also another interafces for ie. for SMS:</p> <pre><code>com....
0
2016-07-14T18:55:54Z
38,387,275
<p>This would be the recommended structure:</p> <pre><code>from my_app.utils import com com.Mail().email_category1(template, ...) </code></pre> <p>where <code>my_app.utils.com</code> is:</p> <pre><code>Mail = CommunicationMail </code></pre> <hr> <p>If you <em>really</em> wanted to keep the <code>com.mail.email_cat...
1
2016-07-15T03:07:18Z
[ "python", "django" ]
Override default _get_for_dict() for ndb Property
38,382,149
<p>i'm having a hard time changing the default _get_for_dict() Method. This is what my code looks at the moment:</p> <pre><code>class ImageProperty(ndb.BlobKeyProperty): def _get_for_dict(self, entity): value = super(ImageProperty, self)._get_for_dict(entity) if value: return images.ge...
2
2016-07-14T18:56:17Z
38,382,257
<p>I haven't tried this, but I <em>think</em> that this would be better as a <code>_from_base_type</code> hook:</p> <pre><code>class ImageProperty(ndb.BlobKeyProperty): def _from_base_type(self, value): return images.get_serving_url(value) </code></pre> <p>If I understand the <a href="https://cloud.google...
1
2016-07-14T19:02:20Z
[ "python", "google-app-engine", "app-engine-ndb", "google-cloud-datastore" ]
Python JSON dictionary key error
38,382,190
<p>I'm trying to collect data from a JSON file using python. I was able to access several chunks of text but when I get to the 3rd object in the JSON file I'm getting a key error. The first three lines work fine but the last line gives me a key error.</p> <pre><code>response = urllib.urlopen("http://asn.desire2learn.c...
-1
2016-07-14T18:58:14Z
38,382,312
<pre><code>topics = data["http://asn.desire2learn.com/resources/D2740436"]["http://purl.org/gem/qualifiers/hasChild"] </code></pre> <p>I don't see this key "<a href="http://asn.desire2learn.com/resources/D2740436" rel="nofollow">http://asn.desire2learn.com/resources/D2740436</a>" anywhere in your source file. You didn...
0
2016-07-14T19:05:49Z
[ "python", "json", "dictionary" ]
Python JSON dictionary key error
38,382,190
<p>I'm trying to collect data from a JSON file using python. I was able to access several chunks of text but when I get to the 3rd object in the JSON file I'm getting a key error. The first three lines work fine but the last line gives me a key error.</p> <pre><code>response = urllib.urlopen("http://asn.desire2learn.c...
-1
2016-07-14T18:58:14Z
38,382,329
<p>The link in your code and your AWS link go to very different files. Open up <a href="http://asn.desire2learn.com/resources/D2740436.json" rel="nofollow">the link in your code</a> in a web browser, and you will find that it's much shorter than the file on AWS. It doesn't actually contain the key you're looking for.</...
0
2016-07-14T19:06:43Z
[ "python", "json", "dictionary" ]
Python JSON dictionary key error
38,382,190
<p>I'm trying to collect data from a JSON file using python. I was able to access several chunks of text but when I get to the 3rd object in the JSON file I'm getting a key error. The first three lines work fine but the last line gives me a key error.</p> <pre><code>response = urllib.urlopen("http://asn.desire2learn.c...
-1
2016-07-14T18:58:14Z
38,382,353
<p>You say that you are using the linked file, in which the key <code>"http://asn.desire2learn.com/resources/S2743916"</code> turns up once.</p> <p>However, your code is downloading a different file - one in which the key does not appear.</p> <p>Try using the file you linked in your code, and you should see the key w...
0
2016-07-14T19:07:56Z
[ "python", "json", "dictionary" ]
python aws put_bucket_policy() MalformedPolicy
38,382,262
<p>How does one use put_bucket_policy()? It throws a MalformedPolicy error even when I try to pass in an existing valid policy:</p> <pre><code>import boto3 client = boto3.client('s3') dict_policy = client.get_bucket_policy(Bucket = 'my_bucket') str_policy = str(dict_policy) response = client.put_bucket_policy(Bucket =...
0
2016-07-14T19:02:38Z
38,382,448
<p>That's because applying <code>str</code> to a <code>dict</code> doesn't turn it into a valid json, use <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow"><code>json.dumps</code></a> instead:</p> <pre><code>import boto3 import json client = boto3.client('s3') dict_policy = client.get_buc...
0
2016-07-14T19:14:11Z
[ "python", "amazon-web-services", "amazon-s3" ]
python aws put_bucket_policy() MalformedPolicy
38,382,262
<p>How does one use put_bucket_policy()? It throws a MalformedPolicy error even when I try to pass in an existing valid policy:</p> <pre><code>import boto3 client = boto3.client('s3') dict_policy = client.get_bucket_policy(Bucket = 'my_bucket') str_policy = str(dict_policy) response = client.put_bucket_policy(Bucket =...
0
2016-07-14T19:02:38Z
38,382,811
<p>Current boto3 API doesn't have a function to APPEND the bucket policy, whether add another items/elements/attributes. You need load and manipulate the JSON yourself. E.g. write script load the policy into a dict, append the "Statement" element list, then use the policy.put to replace the whole policy. Without the...
0
2016-07-14T19:35:36Z
[ "python", "amazon-web-services", "amazon-s3" ]
Python-docx style format
38,382,305
<p>I am using python-docx to output a Pandas DataFrame to a Word table. About a year ago, I wrote this code to build that table, which worked at the time:</p> <pre><code>table = Rpt.add_table(rows=1, cols=(df.shape[1]+1)) table.style = 'LightShading-Accent2' </code></pre> <p>Where <code>Rpt</code> is a Document from...
0
2016-07-14T19:05:29Z
38,385,280
<p>Yes, slightly, apologies for that, but it was the right long-term decision for the API.</p> <p>Try using "Light Shading - Accent 2" instead. It should be the name just as it appears in the Word user interface (UI).</p> <p>If you still can't get it, you can enumerate all the style names with something like this:</p...
1
2016-07-14T22:33:42Z
[ "python", "pandas", "python-docx" ]
How to use groupby agg and rename functions for all columns
38,382,327
<h3>Question</h3> <p><strong><em>How do I get the following result without having to assign a function dictionary for every column?</em></strong></p> <pre><code>df.groupby(level=0).agg({'one': {'SUM': 'sum', 'HowMany': 'count'}, 'two': {'SUM': 'sum', 'HowMany': 'count'}}) </code></pre> <p><a...
3
2016-07-14T19:06:34Z
38,382,429
<p>is using <code>.rename()</code> an option for you?</p> <pre><code>In [7]: df.groupby(level=0).agg(['sum', 'count']).rename(columns=dict(sum='SUM', count='HowMany')) Out[7]: one two SUM HowMany SUM HowMany Alpha A 2 2 4 2 B 10 2 12 2 </code></pre>
3
2016-07-14T19:12:35Z
[ "python", "pandas", "group-by" ]
How to use groupby agg and rename functions for all columns
38,382,327
<h3>Question</h3> <p><strong><em>How do I get the following result without having to assign a function dictionary for every column?</em></strong></p> <pre><code>df.groupby(level=0).agg({'one': {'SUM': 'sum', 'HowMany': 'count'}, 'two': {'SUM': 'sum', 'HowMany': 'count'}}) </code></pre> <p><a...
3
2016-07-14T19:06:34Z
38,382,563
<p>You can use <code>set_levels</code>:</p> <pre><code>g = df.groupby(level=0).agg(['sum', 'count']) g.columns.set_levels(['SUM', 'HowMany'], 1, inplace=True) g &gt;&gt;&gt; one two SUM HowMany SUM HowMany Alpha A 2 2 4 2 B 10 2 12 2 </code></pre>
3
2016-07-14T19:21:14Z
[ "python", "pandas", "group-by" ]