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
Django: send json response from view to a specific template
38,923,165
<p>The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), <strong>as a part of response</strong>. Also, the json response contains <strong>model</strong> and <strong>pk</strong> attribute, I want to remove them and send only the ...
0
2016-08-12T17:05:26Z
38,923,629
<p>The default serializers always add the model and pk so that the data can be deserialized back into objects. Either you can write a custom serializer or can simply remove the unwanted data. </p> <pre><code>personal_details = [pd['fields'] for pd in personal_details] </code></pre> <p>This should give you a new li...
0
2016-08-12T17:37:14Z
[ "python", "json", "django" ]
Django: send json response from view to a specific template
38,923,165
<p>The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), <strong>as a part of response</strong>. Also, the json response contains <strong>model</strong> and <strong>pk</strong> attribute, I want to remove them and send only the ...
0
2016-08-12T17:05:26Z
38,924,020
<p>you can do the following in python2.7</p> <pre><code>import json from django.http import JsonResponse def view_personal_details (request): personal_detail = serializers.serialize('json', personal_details.objects.all()) output = [d['fields'] for d in json.loads(personal_detail)] # return render (reques...
0
2016-08-12T18:04:50Z
[ "python", "json", "django" ]
matplotlib interactive… isn't
38,923,185
<p>I'm running Python 3.5.1 with matplotlib version 1.5.1 and iPython 5.0.0. I can't seem to get matplotlib's interactive feature working. I can run a command to create a plot:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,2,3]) </code></pre> <p>This doesn't show a figure until I...
1
2016-08-12T17:06:25Z
38,923,236
<p>You were probably using interactive mode previously.</p> <p>Start ipython with:</p> <pre><code>ipython --pylab </code></pre> <p>Then your plots will show up instantly.</p>
2
2016-08-12T17:11:16Z
[ "python", "matplotlib", "interactive" ]
Using the .loc function of the pandas dataframe
38,923,280
<p>i have a pandas dataframe whose one of the column is : </p> <pre><code> a = [1,0,1,0,1,3,4,6,4,6] </code></pre> <p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p> <pre><code>a = [1,0,1,0,1,3,4,6,4,6] b = [1,0,1,0,1,1,1,0,1,0] </co...
3
2016-08-12T17:13:57Z
38,923,354
<p>When using comparison operators and boolean logic to filter dataframes you can't use the pythonic idiom of <code>a &lt; myseries &lt; b</code>. Instead you need to <code>(a &lt; myseries) &amp; (myseries &lt; b)</code></p> <pre><code>cond1 = (0 &lt; dtaframe['a']) cond2 = (dtaframe['a'] &lt;= 5) dtaframe['b'] = (c...
3
2016-08-12T17:19:49Z
[ "python", "pandas", "dataframe" ]
Using the .loc function of the pandas dataframe
38,923,280
<p>i have a pandas dataframe whose one of the column is : </p> <pre><code> a = [1,0,1,0,1,3,4,6,4,6] </code></pre> <p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p> <pre><code>a = [1,0,1,0,1,3,4,6,4,6] b = [1,0,1,0,1,1,1,0,1,0] </co...
3
2016-08-12T17:13:57Z
38,923,436
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> to get Boolean values, then <code>astype</code> to convert from Boolean values to 0/1:</p> <pre><code>dtaframe['b'] = dtaframe['a'].between(0, 5, inclusive=False).astype(int...
4
2016-08-12T17:24:24Z
[ "python", "pandas", "dataframe" ]
Using the .loc function of the pandas dataframe
38,923,280
<p>i have a pandas dataframe whose one of the column is : </p> <pre><code> a = [1,0,1,0,1,3,4,6,4,6] </code></pre> <p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p> <pre><code>a = [1,0,1,0,1,3,4,6,4,6] b = [1,0,1,0,1,1,1,0,1,0] </co...
3
2016-08-12T17:13:57Z
38,924,007
<p>Try this with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a>:</p> <pre><code>dtaframe['b'] = np.where(([dtaframe['a'] &gt; 4) | (dtaframe['a']==0),0, dtaframe['a']) </code></pre>
1
2016-08-12T18:03:54Z
[ "python", "pandas", "dataframe" ]
Does tweepy handle rate limit - code 429
38,923,298
<p>I have a wrapper class for the twitter authentication where there is a line: </p> <pre><code>self.__api = tweepy.API(self.auth, wait_on_rate_limit=False, wait_on_rate_limit_notify=False) </code></pre> <p>When I instantiate the wrapper class to get api object of twitt...
0
2016-08-12T17:14:59Z
38,923,993
<p>No, you have to create a handler for this exception.</p>
0
2016-08-12T18:02:58Z
[ "python", "tweepy" ]
Import "request" object in a views' function without pass it as argument
38,923,306
<p>please, I need help with that "request" object that is making me despair...</p> <p>I read that theoretically "request" in views is an "HttpRequest" object but I have a script which needs to call a views.py function, which needs to use that "request" so receive it as argument.</p> <p>Then I tried to import that obj...
-1
2016-08-12T17:15:39Z
38,930,991
<p>I fixed it! The argument with @Daniel Roseman made me realise that I forgot to pass the "request" parameter when I call my script main funcion. That's why my external script "didn't know" what "request" was.</p> <p>Thanks @Daniel Roseman for your patience!</p>
0
2016-08-13T08:52:22Z
[ "python", "django", "parameters", "request", "arguments" ]
Why do some variables need to global while others don't?
38,923,350
<p>In the code below, why do I have to set the <code>num</code> variable to <code>global</code> inside the function but not <code>folder</code> or <code>rename_prefix</code>? If I remove the <code>global</code> from the function, <code>num</code> cannot be used in the function but the <code>folder</code> and <code>rena...
1
2016-08-12T17:19:34Z
38,923,618
<pre><code>x = 0 def function_name(): x = 2 function_name() x #yields:0 </code></pre> <p>but if you define:</p> <pre><code>def function_name(): global x x = 2 </code></pre> <p>then execute</p> <pre><code>function_name() x #yields 2 </code></pre>
1
2016-08-12T17:36:49Z
[ "python", "global-variables" ]
Why do some variables need to global while others don't?
38,923,350
<p>In the code below, why do I have to set the <code>num</code> variable to <code>global</code> inside the function but not <code>folder</code> or <code>rename_prefix</code>? If I remove the <code>global</code> from the function, <code>num</code> cannot be used in the function but the <code>folder</code> and <code>rena...
1
2016-08-12T17:19:34Z
38,923,624
<p>As people in the comments point out, the reason that you don't need to use <code>global</code> for <code>folder</code> and <code>rename_prefix</code> but you do for <code>num</code> is that you're only reading the former two whilst you're setting the latter.</p> <p>If you didn't declare <code>num</code> global, wha...
2
2016-08-12T17:36:56Z
[ "python", "global-variables" ]
Reducing the number of queries in Django
38,923,367
<p>I'm creating a Django app that tracks awards that a person receives. Below is a simplified representation of two models that I have:</p> <pre><code>class AwardHolder(models.Model): name = models.CharField() def get_total_awards(self): entries = self.award_set.all() calc = entries.aggregate(...
1
2016-08-12T17:20:34Z
38,923,739
<p><code>get_all_awards</code> does not necessarily have to call <code>get_total_awards</code>. You're repeating the same query for each entity instead of using a functionality Django already provides: <code>annotate</code>. </p> <p>You can modify <code>get_all_awards</code> to use <code>annotate</code> and use <code>...
1
2016-08-12T17:44:59Z
[ "python", "django" ]
Reducing the number of queries in Django
38,923,367
<p>I'm creating a Django app that tracks awards that a person receives. Below is a simplified representation of two models that I have:</p> <pre><code>class AwardHolder(models.Model): name = models.CharField() def get_total_awards(self): entries = self.award_set.all() calc = entries.aggregate(...
1
2016-08-12T17:20:34Z
38,923,743
<p>Use a model manager to always annotate <code>AwardHolders</code></p> <pre><code>class AwardHolderQuerySet(models.QuerySet): def all(self): return self.annotate(Count('award__units_awarded')) class AwardHolder(models.Model): name = models.CharField() objects = AwardHolderQuerySet.as_manager() ...
1
2016-08-12T17:45:16Z
[ "python", "django" ]
Python Tkinter: how to reopen application by clicking Dock icon on Mac?
38,923,478
<p>I bind the close button with root.withdraw(), so the application will close its window instead of quitting, but seems the application hangs on, and cannot be reopened by clicking Dock icon</p> <p>How to bind the method root.deiconify() to do this?</p> <p>I package the application with pyinstaller</p> <p>Update: T...
-2
2016-08-12T17:26:42Z
38,924,838
<p>If you are using OS X 10.9 or later and a Python from a python.org 64-bit/32-bit installer, application windows may not update properly due to a Tk problem. Install the latest ActiveTcl 8.5.18.0 if possible. (Also, a critical OS X 10.9 problem that could cause Python to crash when used interactively has been fixed a...
0
2016-08-12T19:00:31Z
[ "python", "tkinter" ]
Python Tkinter: how to reopen application by clicking Dock icon on Mac?
38,923,478
<p>I bind the close button with root.withdraw(), so the application will close its window instead of quitting, but seems the application hangs on, and cannot be reopened by clicking Dock icon</p> <p>How to bind the method root.deiconify() to do this?</p> <p>I package the application with pyinstaller</p> <p>Update: T...
-2
2016-08-12T17:26:42Z
38,967,103
<p>Finally I found the solution from here <a href="http://www.tkdocs.com/tutorial/menus.html" rel="nofollow">http://www.tkdocs.com/tutorial/menus.html</a></p> <pre><code>root.createcommand('tk::mac::ReopenApplication', root.deiconify) </code></pre>
0
2016-08-16T05:17:35Z
[ "python", "tkinter" ]
Infeasible solution with redundant constraints - PuLP and COIN-OR
38,923,713
<p>im working with an LP model in python using <code>PuLP</code> with <code>CBC</code>. The model has a lot of constraints, and of course many of them are redundant. i will show an example of that. </p> <pre><code>#import libraries from pulp import LpVariable, LpProblem, LpMaximize, lpSum, LpConstraint, LpStatus, valu...
0
2016-08-12T17:43:01Z
38,924,225
<p>I didn't use pulp much, so i can't explain the internals here (which make your case fail), but <em>you are using pulp's constraint-mechanism in a wrong way</em>.</p> <h3>Your approach (fails):</h3> <pre><code>for i in set_pt: prob += LpConstraint(var[i] &lt;= 300000), "max margin "+str(i) prob += LpConstr...
0
2016-08-12T18:19:45Z
[ "python", "constraints", "linear-programming", "pulp", "coin-or-cbc" ]
Very weird python flask behaviour
38,923,728
<p>When ever I access my python flask website and go to myurl.com/newuser I get the necessary html page returned. this page has a submit button and it is supposed to pass info to the the server when pressed. but when it is pressed it redirects me to the 'index' method of the website and the information is not passed on...
-6
2016-08-12T17:44:05Z
38,930,365
<p>Like Martijn said, change </p> <pre><code> usernameSet = Users(username=request.form["Username"]) passwordSet = Users(password=request.form["Password"]) db.session.add(usernameSet) db.session.add(passwordSet) </code></pre> <p>to</p> <pre><code> user = Users(username=request.form["Username"], pas...
0
2016-08-13T07:30:24Z
[ "python", "flask" ]
Assign multiple values to multiple slices of a numpy array at once
38,923,763
<p>I have a numpy array, a list of start/end indexes that define ranges within the array, and a list of values, where the number of values is the same as the number of ranges. Doing this assignment in a loop is currently very slow, so I'd like to assign the values to the corresponding ranges in the array in a vectorize...
1
2016-08-12T17:46:45Z
38,924,029
<p>One possibility is to zip the start, end index with the values and broadcast the index and values manually:</p> <pre><code>starts = [0, 2, 4, 6] ends = [2, 4, 6, 8] values = [1, 2, 3, 4] a = np.zeros(10) import numpy as np # calculate the index array and value array by zipping the starts, ends and values and expan...
1
2016-08-12T18:05:22Z
[ "python", "numpy", "vectorization" ]
Assign multiple values to multiple slices of a numpy array at once
38,923,763
<p>I have a numpy array, a list of start/end indexes that define ranges within the array, and a list of values, where the number of values is the same as the number of ranges. Doing this assignment in a loop is currently very slow, so I'd like to assign the values to the corresponding ranges in the array in a vectorize...
1
2016-08-12T17:46:45Z
38,924,976
<p>This will do the trick in a fully vectorized manner:</p> <pre><code>counts = ends - starts idx = np.ones(counts.sum(), dtype=np.int) idx[np.cumsum(counts)[:-1]] -= counts[:-1] idx = np.cumsum(idx) - 1 + np.repeat(starts, counts) a[idx] = np.repeat(values, count) </code></pre>
1
2016-08-12T19:12:04Z
[ "python", "numpy", "vectorization" ]
Python pexpect: var.expect('string') not returning expected values when 'string' isn't found
38,923,804
<p>I am working with the following bit of Python code. The code is fairly simple, pexpect sends <code>echo testcase</code> to the terminal, then monitors the terminal for the subsequent appearance of <code>testcase</code>, then verifies that it saw the echo by setting <code>bool_value=True</code> (assuming it sees the ...
0
2016-08-12T17:49:23Z
38,924,591
<p>It turns out that when the system was not outputting something <code>pexpect</code> was looking for, it would hit <code>pexpect.EOF</code> without triggering any sort of action. Because I don't tell it what to do when it hits EOF without seeing any other strings it's expecting, it returns an exception instead.</p> ...
0
2016-08-12T18:46:02Z
[ "python", "python-2.7", "pexpect" ]
Python script not entering for loop
38,923,891
<p>I'm writing a script from a tutorial I found online that essentially just reads the news. The script now compiles and launches, but doesn't actually do anything. After debugging, I found that it doesn't enter into the for-loop, and I'm not sure why. </p> <pre><code>import subprocess import requests from bs4 import ...
-1
2016-08-12T17:56:49Z
38,923,985
<p>You have a typo on this line</p> <pre><code>g_data = soup.find_all("div",{"class":"natory_intro"}) </code></pre> <p>Should be</p> <pre><code>g_data = soup.find_all("div",{"class":"nstory_intro"}) </code></pre>
2
2016-08-12T18:02:33Z
[ "python", "beautifulsoup", "raspberry-pi" ]
Python script not entering for loop
38,923,891
<p>I'm writing a script from a tutorial I found online that essentially just reads the news. The script now compiles and launches, but doesn't actually do anything. After debugging, I found that it doesn't enter into the for-loop, and I'm not sure why. </p> <pre><code>import subprocess import requests from bs4 import ...
-1
2016-08-12T17:56:49Z
38,924,051
<p>I think it doesn't enter the loop because <code>g_data</code> is an empty list.</p> <p>Check the website, make sure you can get items by class name <code>"natory_intro"</code>.</p> <p>I run:</p> <pre><code>import subprocess import requests from bs4 import BeautifulSoup import textwrap head = 'mpg123 -q ' tail = ...
0
2016-08-12T18:06:56Z
[ "python", "beautifulsoup", "raspberry-pi" ]
Making an animation of Newton's Method for finding roots of a function
38,923,909
<p>Earlier for my Calculus class, I had the idea to create a graph that would update itself to show the progression of Newton's Method for finding the roots of a function. So my question was, using Python and Sympy to handle all the messing calculus behind the issue, how was I going to graph this in an informative way....
0
2016-08-12T17:57:38Z
38,923,910
<p>After about 2 days of work I've managed to come up with this solution however. I am still using Sympy as the backend for derivative computation and function input, but I am converting those expressions into lambda functions to generate values that I can feed into coordinates for Matplotlib. I've also cleaned up the ...
0
2016-08-12T17:57:38Z
[ "python", "matplotlib", "graph", "sympy", "newtons-method" ]
Numpy array from characters in BDF file
38,923,943
<p>I have a file, font_file.bdf, and need to get the characters contained in it as numpy arrays where each element is one pixel.</p> <p>Here's the snippet of that file which defines the '?' character:</p> <pre><code>STARTCHAR question ENCODING 63 SWIDTH 1000 0 DWIDTH 6 0 BBX 5 7 0 0 BITMAP 70 88 08 10 20 00 20 ENDCHA...
1
2016-08-12T17:59:53Z
39,020,645
<p>It turns out the unexpected behavior I was seeing was due to a bug in PIL as described in this SO question: <a href="http://stackoverflow.com/questions/2761645/error-converting-pil-bw-images-to-numpy-arrays">Error Converting PIL B&amp;W images to Numpy Arrays</a>.</p> <p>So the key to solving my problem was to conv...
0
2016-08-18T14:20:25Z
[ "python", "numpy", "fonts", "bitmap", "python-imaging-library" ]
Variable with List comprehension
38,923,962
<p>I'm trying to rewrite my old code using list comprehension and I was wondering if there's a way to use a variable called "result" instead of <code>int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)]))</code> in the code below, because I will need to reuse it within the function.</p> <pre><code>l...
0
2016-08-12T18:01:06Z
38,924,226
<p>Not really sure what you're trying to do, but the function I wrote below behaves equivalent to yours up until the line <code>most_common = lst.count()</code> which is invalid, as Chris Rands points out in the comments.</p> <p>If you clarify what it is you're actually trying to achieve, I can edit this code accordin...
0
2016-08-12T18:19:51Z
[ "python", "list", "for-loop", "list-comprehension" ]
Variable with List comprehension
38,923,962
<p>I'm trying to rewrite my old code using list comprehension and I was wondering if there's a way to use a variable called "result" instead of <code>int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)]))</code> in the code below, because I will need to reuse it within the function.</p> <pre><code>l...
0
2016-08-12T18:01:06Z
38,924,261
<p><code>sorted_l[sorted_l.index(i)]</code> is the exact same as <code>i</code>. </p> <p><code>sorted_l1[sorted_l1.index(i1)]</code> is the exact same as <code>i1</code>. </p> <p>You are doing integer division, which truncates the decimal, so what are you rounding?</p> <pre><code>int(round( v1 // v2 )) </code></pre>...
1
2016-08-12T18:22:07Z
[ "python", "list", "for-loop", "list-comprehension" ]
Object going out of scope and being garbage collected in PySide/PyQt
38,923,978
<p>I'm having issues with a non-Qt object falling out of scope and being garbage collected by Python. In the generic example below, I create an object when one button is clicked and want to use that object when the other button is clicked. After the slot for the 1st button is finished executing, the object is garbage c...
1
2016-08-12T18:02:11Z
38,927,433
<p>Create a subclass of <code>QWidget</code> to keep all the child objects as attributes:</p> <pre><code>import sys from PySide import QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.resize(250, 150) self.setWindowTitle('Example...
0
2016-08-12T22:48:08Z
[ "python", "qt", "garbage-collection", "pyqt", "pyside" ]
Object going out of scope and being garbage collected in PySide/PyQt
38,923,978
<p>I'm having issues with a non-Qt object falling out of scope and being garbage collected by Python. In the generic example below, I create an object when one button is clicked and want to use that object when the other button is clicked. After the slot for the 1st button is finished executing, the object is garbage c...
1
2016-08-12T18:02:11Z
38,928,325
<p>It is being garbage collected because the scope is lost once the function execution ends. You need to save the reference, and there are two ways of doing it:</p> <ol> <li>Save the object in a global variable, so it won't get collected by the gc and also stay accessible on the other function.</li> <li>Wrap the whole...
0
2016-08-13T01:22:46Z
[ "python", "qt", "garbage-collection", "pyqt", "pyside" ]
Tkinter, show Calendar in Toplevel window on button click
38,924,167
<p>I deleted my previous question about this in order to simplify my question and communicate the question clearer. I've got a project with multiple classes inside of it and I'd like to get a Calendar to display in a new window once I click a button. I am currently using <a href="http://svn.python.org/projects/sandbox/...
0
2016-08-12T18:14:59Z
38,924,333
<pre><code>self.calendar = Calendar(self) </code></pre> <p>Putting this line within your application <code>init</code> will create it at the same time that the application is created. You would want to move this into your <code>show_Calendar</code> method.</p> <pre><code>def show_Calendar(self): '''shows calendar...
1
2016-08-12T18:26:18Z
[ "python", "tkinter", "calendar" ]
Django's Count with relationship spans
38,924,248
<p>Here are the relevant models:</p> <pre><code>class WhatToWearCandidates(models.Model): profile = models.ForeignKey(Profile, null=False, blank=False, related_name="outfit_candidates") look = models.ForeignKey(StyleLook, null=False, blank=False, related_name="outfit_candidates") class StyleLook(models.Model)...
1
2016-08-12T18:21:02Z
38,928,823
<p>I think you're probably running into problems with <a href="https://docs.djangoproject.com/en/stable/topics/db/aggregation/#interaction-with-default-ordering-or-order-by" rel="nofollow">default ordering</a> in one of your models. Try adding <code>.order_by()</code> to the end of the query:</p> <pre><code>all_candid...
0
2016-08-13T03:12:02Z
[ "python", "django", "count" ]
Creating a Nested List in Python
38,924,256
<p>I'm trying to make a nested list in Python to contain information about points in a video, and I'm having a lot of trouble creating an array for the results to be saved in to. The structure of the list is simple: the top level is a reference to the frame, the next level is a reference to a marker, and the last level...
0
2016-08-12T18:21:39Z
38,925,623
<p>This illustrates what is going on:</p> <pre><code>In [1334]: step=[[0]*3 for x in range(3)] In [1335]: step Out[1335]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] In [1336]: stack=[step]*4 In [1337]: stack Out[1337]: [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], ...
1
2016-08-12T19:58:31Z
[ "python", "python-2.7", "numpy" ]
How to create multiple types of user with custom user model in django?
38,924,271
<p>I want to create multiple types of user in django app e.g one for Company and one for Employee.</p> <p>What I had in mind was company will signup for itself and then employees will be created by company admin through his/her dashboard.</p> <p>After creation employees will sign in directly.</p> <p>So (if possible)...
0
2016-08-12T18:22:44Z
38,925,133
<p>You can just create groups for the different types of users:</p> <pre><code>Group.objects.create(name='Company') </code></pre> <p>And then assign the user to the appropriate group:</p> <pre><code>user.groups.add(group) </code></pre> <p>The last thing it sounds like you could do is to associate employees with the...
0
2016-08-12T19:22:10Z
[ "python", "django", "multiple-users", "django-custom-user" ]
python3 strftime output varies by platform
38,924,289
<p>Python3 <code>strftime</code> produces results that vary by platform. For example:</p> <p>OS X 10.10.5</p> <pre><code>&gt;&gt;&gt; sys.version '3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]' &gt;&gt;&gt; datetime.datetime(1, 1, 1, 0, 0).strftime('%Y/%m/%d') '0001/...
3
2016-08-12T18:23:59Z
38,924,621
<p><code>strftime</code> is just a thin-wrapper around the <code>strftime</code> function defined in the <code>C</code> library you're using. See a related 'bug' <a href="http://bugs.python.org/issue9811" rel="nofollow">here</a>. This behavior <em>seems</em> to be another case of exactly that.</p> <p>Differences betwe...
2
2016-08-12T18:47:55Z
[ "python", "python-3.x", "strftime" ]
Sorting Python list
38,924,305
<p>I'm having trouble with my code sorting correctly. </p> <pre><code>def generateList(attendeeList, criteria, workshoptitle): for i in attendeeList: if(criteria == 'Workshop1'): criteria = 'Workshop B' if(i['session1'] == criteria ): temp = [] temp.append((i['lastna...
0
2016-08-12T18:24:52Z
38,924,336
<p>Each time through the loop, you're just printing a list with a single item in it.</p> <pre><code>temp = [] # empty list temp.append((i['lastname'])) # list with one element temp.sort() # list is already sorted (since it just has one element) print(temp) </code></pre> <p>Maybe you wanted something like this:</p> <...
3
2016-08-12T18:26:40Z
[ "python" ]
Sorting Python list
38,924,305
<p>I'm having trouble with my code sorting correctly. </p> <pre><code>def generateList(attendeeList, criteria, workshoptitle): for i in attendeeList: if(criteria == 'Workshop1'): criteria = 'Workshop B' if(i['session1'] == criteria ): temp = [] temp.append((i['lastna...
0
2016-08-12T18:24:52Z
38,924,381
<p>Your code does not do what you intend. Even if you do print the item each time you get it, you generate an empty list at each iteration.</p> <p>You want to create the list before the loop, in the function body, then append to it, then sort it, then iterate through it if you want to additionally print it :</p> <pre...
0
2016-08-12T18:29:46Z
[ "python" ]
decimal.Decimal(n) % 1 returns InvalidOperation, DivisionImpossible for all n >= 100
38,924,369
<p>I am using Decimal objects in a django app, and found this strange error:</p> <pre><code>ipdb&gt; decimal.Decimal(10) % 1 Decimal('0') ipdb&gt; decimal.Decimal(100) % 1 *** decimal.InvalidOperation: [&lt;class 'decimal.DivisionImpossible'&gt;] ipdb&gt; decimal.Decimal(150) % 1 *** decimal.InvalidOperati...
7
2016-08-12T18:29:00Z
38,924,572
<p>I think I figured it out.</p> <p>Looking at the <a href="https://svn.python.org/projects/python/tags/r32/Lib/decimal.py" rel="nofollow">source code</a>, I found this:</p> <pre><code># catch most cases of large or small quotient expdiff = self.adjusted() - other.adjusted() if expdiff &gt;= context.prec + 1: # e...
4
2016-08-12T18:44:44Z
[ "python", "django", "decimal", "python-3.5" ]
Plucking an inner most item by its index with list comprehension
38,924,373
<p>I'm trying to get better at understanding list comprehension, and I started this thing with a list of tuples that I've cast to a list of lists.</p> <p>With list comprehension, how can I pluck out from the inner most list's index that contains a <code>2</code> in the last index?</p> <pre><code>results = [ [ [...
0
2016-08-12T18:29:15Z
38,924,423
<pre><code>results = [[x for x in lst if x[-1]!=2] for lst in results] </code></pre>
2
2016-08-12T18:34:03Z
[ "python", "list-comprehension" ]
Plucking an inner most item by its index with list comprehension
38,924,373
<p>I'm trying to get better at understanding list comprehension, and I started this thing with a list of tuples that I've cast to a list of lists.</p> <p>With list comprehension, how can I pluck out from the inner most list's index that contains a <code>2</code> in the last index?</p> <pre><code>results = [ [ [...
0
2016-08-12T18:29:15Z
38,924,497
<p>Something like this:</p> <pre><code>results_not_ending_in_2 = [ [inner_list for inner_list in outer_list if inner_list[-1] != 2] for outer_list in results ] </code></pre>
0
2016-08-12T18:39:18Z
[ "python", "list-comprehension" ]
Is there a standard way to partition an interable into equivalence classes given a relation in python?
38,924,421
<p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> ...
4
2016-08-12T18:33:57Z
38,924,561
<pre><code>In [1]: def my_relation(x): ...: return x % 3 ...: In [2]: from collections import defaultdict In [3]: def partition(X, relation): ...: d = defaultdict(list) ...: for item in X: ...: d[my_relation(item)].append(item) ...: return d.values() ...: In [4]: X = [1, ...
1
2016-08-12T18:43:47Z
[ "python", "equivalence-classes" ]
Is there a standard way to partition an interable into equivalence classes given a relation in python?
38,924,421
<p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> ...
4
2016-08-12T18:33:57Z
38,924,631
<p>I found <a href="http://code.activestate.com/recipes/499354-equivalence-partition/" rel="nofollow">this Python recipe</a> by John Reid. It was written in Python 2 and I adapted it to Python 3 to test it. The recipe includes a test to partition the set of integers <code>[-3,5)</code> into equivalence classes based on...
1
2016-08-12T18:48:24Z
[ "python", "equivalence-classes" ]
Is there a standard way to partition an interable into equivalence classes given a relation in python?
38,924,421
<p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> ...
4
2016-08-12T18:33:57Z
38,924,644
<p>The following function takes an iterable <code>a</code>, and an equivalence function <code>equiv</code>, and does what you ask:</p> <pre><code>def partition(a, equiv): partitions = [] # Found partitions for e in a: # Loop over each element found = False # Note it is not yet part of a know partition ...
1
2016-08-12T18:49:17Z
[ "python", "equivalence-classes" ]
Is there a standard way to partition an interable into equivalence classes given a relation in python?
38,924,421
<p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> ...
4
2016-08-12T18:33:57Z
38,924,686
<p>Would this work ?</p> <pre><code>def equivalence_partition(iterable, relation): classes = defaultdict(set) for element in iterable: for sample, known in classes.items(): if relation(sample, element): known.add(element) break else: class...
0
2016-08-12T18:51:34Z
[ "python", "equivalence-classes" ]
Is there a standard way to partition an interable into equivalence classes given a relation in python?
38,924,421
<p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> ...
4
2016-08-12T18:33:57Z
38,924,694
<p>I'm not aware of any python library dealing with equivalence relations.</p> <p>Perhaps this snippet is useful:</p> <pre><code>def rel(x1, x2): return x1 % 5 == x2 % 5 data = range(18) eqclasses = [] for x in data: for eqcls in eqclasses: if rel(x, eqcls[0]): # x is a member of this ...
1
2016-08-12T18:51:54Z
[ "python", "equivalence-classes" ]
How can I pause Monkeyrunner for user input?
38,924,498
<p>If I am running in monkeyrunner and want the user to be able to input something into my python script while my program is running how can I do that?</p> <p>Currently <code>input()</code> never registers that I hit enter.</p> <p>I don't know why this is. I have searched yesterday and today, and found no answer.<br>...
1
2016-08-12T18:39:26Z
38,956,880
<p>You can try <a href="https://github.com/dtmilano/AndroidViewClient" rel="nofollow">AndroidViewClient/culebra</a> which is a drop-in replacement for <code>monkeyrunner</code> in 99% of the cases and because it's python you won't have to deal with those jython problems.</p>
0
2016-08-15T14:19:10Z
[ "android", "python", "monkeyrunner" ]
Tensorflow 0.10 (CUDA) on OSX segfaults on python import
38,924,568
<p>I've been trying to get tensorflow 0.10 up and running on my El Capitan Macbook Pro (Late 2013, GeForce GT 750M), so far without success. I've tried the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html" rel="nofollow">official tensorflow documentation's instructions</a> and a number of ot...
3
2016-08-12T18:44:29Z
38,927,238
<p>The problem is described in this comment: <a href="https://github.com/tensorflow/tensorflow/issues/2940#issuecomment-238952433" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/2940#issuecomment-238952433</a></p> <p>"There is a bug with loading libcuda.dylib - the default cuda install creates libcuda....
2
2016-08-12T22:24:08Z
[ "python", "osx", "tensorflow" ]
Python/Django pass user input as keyword arguments?
38,924,574
<p>I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.</p> <pre><code>HTML: &lt;p class="search"&gt; &lt;form method="GET" action="{% url 'job' %}" class="sidebar-form"&gt;...
-2
2016-08-12T18:44:48Z
38,924,730
<p>What you want doesn't make sense. The <code>{{ }}</code> signs denote a context variable which is passed into the template from the server, before the template is rendered. But you're trying to use a value which is only defined when the user actually types something into the rendered page itself.</p> <p>You could p...
1
2016-08-12T18:54:16Z
[ "python", "html", "django", "forms", "url" ]
Python/Django pass user input as keyword arguments?
38,924,574
<p>I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.</p> <pre><code>HTML: &lt;p class="search"&gt; &lt;form method="GET" action="{% url 'job' %}" class="sidebar-form"&gt;...
-2
2016-08-12T18:44:48Z
39,166,672
<p>I decided to just go with javascript since my django code was not working with a request method when refreshing the page.</p>
0
2016-08-26T12:43:58Z
[ "python", "html", "django", "forms", "url" ]
unordered_map<int, vector<float>> equivalent in Python
38,924,598
<p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p> <pre><code>[0] = {1.0, 1.0, 1.0, 1.0} [1] = {0.5, 1.0} </code></pre> <p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p> <pre><code>std::unord...
1
2016-08-12T18:46:44Z
38,924,653
<p>I would go for a <code>dict</code> with integers as keys and <code>list</code> as items, e.g.</p> <pre><code>m = dict() m[0] = list() m[0].append(1.0) m[0].append(0.5) m[13] = list() m[13].append(13.0) </code></pre> <p>if it is not too much data</p>
0
2016-08-12T18:49:40Z
[ "python", "c++", "hashmap" ]
unordered_map<int, vector<float>> equivalent in Python
38,924,598
<p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p> <pre><code>[0] = {1.0, 1.0, 1.0, 1.0} [1] = {0.5, 1.0} </code></pre> <p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p> <pre><code>std::unord...
1
2016-08-12T18:46:44Z
38,924,673
<p>How about dictionary and lists like this:</p> <pre><code>&gt;&gt;&gt; d = {0: [1.0, 1.0, 1.0, 1.0], 1: [0.5, 1.0]} &gt;&gt;&gt; d[0] [1.0, 1.0, 1.0, 1.0] &gt;&gt;&gt; d[1] [0.5, 1.0] &gt;&gt;&gt; </code></pre> <p>The key can be integers and associated values can be stored as a list. Dictionary in Python is a hash...
2
2016-08-12T18:50:35Z
[ "python", "c++", "hashmap" ]
unordered_map<int, vector<float>> equivalent in Python
38,924,598
<p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p> <pre><code>[0] = {1.0, 1.0, 1.0, 1.0} [1] = {0.5, 1.0} </code></pre> <p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p> <pre><code>std::unord...
1
2016-08-12T18:46:44Z
38,924,684
<p>A <strong><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a></strong> of this format -> <code>{ (int) key : (list) value }</code></p> <pre><code>d = {} # Initialize empty dictionary. d[0] = [1.0, 1.0, 1.0, 1.0] # Place key 0 in d, and map this array to it. ...
1
2016-08-12T18:51:21Z
[ "python", "c++", "hashmap" ]
Reading data in excel in python
38,924,642
<p>I basically have a text file with data as: </p> <pre><code>Neighbor V State/Pf 10.230.2.91 4 1178 10.229.5.239 4 1177 10.229.6.239 4 1173 </code></pre> <p>I want to read the values under neighbor column and put in excel. How can I achieve this? I am new to python, so ple...
-3
2016-08-12T18:49:14Z
38,924,758
<p>Pandas has methods to transform data frames into Excel files (<code>pd.DataFrame.to_excel</code>), but I agree with bernie: It is not very clear how your data look like</p> <p><strong>UPDATE</strong></p> <p>So it would look like</p> <pre><code>l = list(["Neighbor","10.230.2.91","10.229.5.239","10.229.6.239"]) df ...
0
2016-08-12T18:56:15Z
[ "python", "excel" ]
Reading data in excel in python
38,924,642
<p>I basically have a text file with data as: </p> <pre><code>Neighbor V State/Pf 10.230.2.91 4 1178 10.229.5.239 4 1177 10.229.6.239 4 1173 </code></pre> <p>I want to read the values under neighbor column and put in excel. How can I achieve this? I am new to python, so ple...
-3
2016-08-12T18:49:14Z
38,924,785
<p>You'll want something simple that can output to a excel file.</p> <p>You'll want to split your line into separate lines and only extract the parts that you want. In your case the <code>.split()</code> method would be very helpful. <code>.split()</code> takes your string and splits it based on the delimiter given (d...
0
2016-08-12T18:57:59Z
[ "python", "excel" ]
Clarification about Python imports
38,924,645
<p>What's the difference between <code>from foo import bar</code>and <code>import foo.bar as bar</code>?</p> <p>Is there any difference as far as Python namespaces and scope are concerned? If you want to use something from <code>bar</code> (say a function called <code>whatever</code>), you'd call it as <code>bar.whate...
5
2016-08-12T18:49:20Z
38,924,783
<p>When bar is not a module, there is a huge difference:</p> <pre><code># foo.py bar = object() </code></pre> <p>Here <code>from foo import bar</code> would be normal in python, but <code>import foo.bar as bar</code> would raise an <code>ImportError: No module named bar</code>.</p> <p>Usually we only use the "as" co...
5
2016-08-12T18:57:54Z
[ "python", "python-import" ]
Clarification about Python imports
38,924,645
<p>What's the difference between <code>from foo import bar</code>and <code>import foo.bar as bar</code>?</p> <p>Is there any difference as far as Python namespaces and scope are concerned? If you want to use something from <code>bar</code> (say a function called <code>whatever</code>), you'd call it as <code>bar.whate...
5
2016-08-12T18:49:20Z
38,924,784
<p>There is a difference, both for when there is a <code>bar</code> module or package inside the <code>foo</code> package, and if <code>bar</code> is <em>not a module at all</em>.</p> <p>Considered the following <code>foo</code> package:</p> <pre><code>foo/ __init__.py bar.py </code></pre> <p>If the <code>__...
4
2016-08-12T18:57:55Z
[ "python", "python-import" ]
Why I get random result from seemingly non-random code with python sklearn?
38,924,726
<h3>I updated the question based on the responses.</h3> <p>I have a list of strings named "str_tuple". I want to compute some similarity measures between the first element in the list and the rest of the elements. I run the following six-line code snippet. </p> <p>What completely baffles me is that the outcome seems ...
1
2016-08-12T18:54:06Z
38,924,895
<p>By default, <code>Truncated SVD</code> follows a randomized algorithm. So, you must specify the <code>RandomState</code> value to be set as <code>numpy.random.seed</code> value.</p> <pre><code>cmat = TruncatedSVD(n_components=2, random_state=42).fit_transform(cmat) </code></pre> <blockquote> <p><strong><a href="...
3
2016-08-12T19:04:51Z
[ "python", "random", "machine-learning", "scikit-learn" ]
Pass extra arguments to nested Serializer in Django Rest Framework
38,924,742
<p>I have such serializer:</p> <pre><code> class FirstModelSerializer(serializers.ModelSerializer): secondModel = SecondModelSerializer() class Meta: model = FirstModel fields = '__all__' </code></pre> <p>Where secondModel is ManyToMany field of FirstModel.</p> <p>Is there any...
0
2016-08-12T18:54:44Z
38,929,312
<p>It was easier then I thought. I just had to use context like this</p> <pre><code>class FirstModelSerializer(serializers.ModelSerializer): secondModel = SerializerMethodField() class Meta: model = FirstModel fields = '__all__' def get_secondModel(self, obj): ret...
1
2016-08-13T04:50:01Z
[ "python", "django", "django-rest-framework" ]
Reading in multiple files in directory using python
38,924,803
<p>I'm trying to open each file from a directory and print the contents, so I have a code as such:</p> <pre><code>import os, sys def printFiles(dir): os.chdir(dir) for f in os.listdir(dir): myFile = open(f,'r') lines = myFile.read() print lines myFile.close() printFiles(sys.ar...
0
2016-08-12T18:59:04Z
38,925,006
<p>The code itself certainly should print the contents of every file. However, if you supply a local path and not a global path it will not work.</p> <p>For example, imagine you have the following folder structure:</p> <pre><code>./a ./a/x.txt ./a/y.txt ./a/a ./a/a/x.txt </code></pre> <p>If you now run</p> <pre><c...
0
2016-08-12T19:13:54Z
[ "python" ]
Reading in multiple files in directory using python
38,924,803
<p>I'm trying to open each file from a directory and print the contents, so I have a code as such:</p> <pre><code>import os, sys def printFiles(dir): os.chdir(dir) for f in os.listdir(dir): myFile = open(f,'r') lines = myFile.read() print lines myFile.close() printFiles(sys.ar...
0
2016-08-12T18:59:04Z
38,925,260
<p>There is problem with directory and file paths.</p> <p>Option 1 - chdir:</p> <pre><code>def printFiles(dir): os.chdir(dir) for f in os.listdir('.'): myFile = open(f,'r') # ... </code></pre> <p>Option 2 - computing full path:</p> <pre><code>def printFiles(dir): # no chdir here for ...
1
2016-08-12T19:30:44Z
[ "python" ]
Combining tuple elements from a list of tuples. Tuple elements are tuple and list
38,924,829
<p>I'm relatively new with Python and am having a hard time coming up with a way to make the following work. Currently, I have a list of tuples (larger than <code>list_one</code>. The elements inside these tuples are 1) a tuple, and 2) a string (these strings are always one of two values: in the example <code>'A'</cod...
2
2016-08-12T19:00:13Z
38,926,100
<p><strong>Edit</strong></p> <p>This solves a related question, whereby all the lists corresponding to <code>'A'</code> and <code>'B'</code> values are aggregated, and the id is chose of the total first id for each group.</p> <hr> <p>Here you go </p> <pre><code>letterKeyToFirstIDMap = {} result_dict = {} for tpl i...
1
2016-08-12T20:36:30Z
[ "python", "list" ]
Combining tuple elements from a list of tuples. Tuple elements are tuple and list
38,924,829
<p>I'm relatively new with Python and am having a hard time coming up with a way to make the following work. Currently, I have a list of tuples (larger than <code>list_one</code>. The elements inside these tuples are 1) a tuple, and 2) a string (these strings are always one of two values: in the example <code>'A'</cod...
2
2016-08-12T19:00:13Z
38,926,128
<p>You can basically loop along, remembering what is the current key (initialized to <code>None</code>). </p> <pre><code>key = None # This is 'A' or 'B' in your example, but it starts off as None new_list = [] # This holds the final result for r, l in [(r, l) for (l, r) in list_one]: if r != key: # If the current...
1
2016-08-12T20:39:13Z
[ "python", "list" ]
Parse non-standard semicolon separated "JSON"
38,924,902
<p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally p...
1
2016-08-12T19:05:16Z
38,925,163
<p>Use the Python <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow"><code>tokenize</code> module</a> to transform the text stream to one with commas instead of semicolons. The Python tokenizer is happy to handle JSON input too, even including semicolons. The tokenizer presents strings as <em>whol...
6
2016-08-12T19:24:08Z
[ "python", "json", "parsing" ]
Parse non-standard semicolon separated "JSON"
38,924,902
<p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally p...
1
2016-08-12T19:05:16Z
38,925,263
<p>You can do some odd things and get it (probably) right.</p> <p>Because strings on JSON cannot have control chars such as <code>\t</code>, you could replace every <code>;</code> to <code>\t,</code> so the file will be parsed correctly if your JSON parser is able to load non strict JSON (such as Python's).</p> <p>Af...
0
2016-08-12T19:30:53Z
[ "python", "json", "parsing" ]
Parse non-standard semicolon separated "JSON"
38,924,902
<p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally p...
1
2016-08-12T19:05:16Z
38,925,348
<p>Using a simple character state machine, you can convert this text back to valid JSON. The basic thing we need to handle is to determine the current "state" (whether we are escaping a character, in a string, list, dictionary, etc), and replace ';' by ',' when in a certain state.</p> <p>I don't know if this is proper...
0
2016-08-12T19:38:17Z
[ "python", "json", "parsing" ]
Parse non-standard semicolon separated "JSON"
38,924,902
<p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally p...
1
2016-08-12T19:05:16Z
38,933,822
<p>Pyparsing makes it easy to write a string transformer. Write an expression for the string to be changed, and add a parse action (a parse-time callback) to replace the matched text with what you want. If you need to avoid some cases (like quoted strings or comments), then include them in the scanner, but just leave t...
0
2016-08-13T14:40:55Z
[ "python", "json", "parsing" ]
Copying partial list in python
38,924,992
<p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy on...
0
2016-08-12T19:12:44Z
38,925,049
<p><code>li</code> is value in the <code>allTickets</code> (which I guess is String). You are passing that to get value <code>allTickets[ii]</code>. Array/list index are always integers. </p> <p>I think you are looking for something like:</p> <pre><code>for index, val in ......... if lastTicket in allTickets[in...
-1
2016-08-12T19:16:17Z
[ "python", "list" ]
Copying partial list in python
38,924,992
<p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy on...
0
2016-08-12T19:12:44Z
38,925,063
<p>use either</p> <pre><code>for ii in range(len(allTickets)): if lastTicket in allTickets[ii]: idx = ii break </code></pre> <p>BTW are you sure you want <code>if lastTicket in allTickets[ii]:</code> and not <code>if lastTicket == allTickets[ii]:</code>? </p>
1
2016-08-12T19:17:16Z
[ "python", "list" ]
Copying partial list in python
38,924,992
<p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy on...
0
2016-08-12T19:12:44Z
38,925,486
<p>Use <code>enumerate</code> to get an index:</p> <pre><code>for idx, ticket in enumerate(allTickets): if lastTicket in ticket: break print idx tickets = allTickets[idx:] </code></pre>
0
2016-08-12T19:47:58Z
[ "python", "list" ]
How do I unit test HTTP Digest Authentication in Flask?
38,925,016
<p>I've got a flask app that implements a REST api. For reasons, I'm using HTTP Digest Authentication. I've used the Flask-HTTPAuth library to implement the digest authentication and it works; however, I am unable to authenticate in the unit tests. </p> <p>For the unit tests, prior to setting up the authentication, I'...
2
2016-08-12T19:14:18Z
38,925,124
<p>It's not neccessary to use real-world authentication in tests. Either disable authentication when running tests or create test user and use this test user in tests.</p> <p>For example:</p> <pre><code> @digest_auth.get_password def get_pw(username): if running_from_tests(): if username ==...
0
2016-08-12T19:21:37Z
[ "python", "flask", "python-unittest", "digest-authentication", "flask-httpauth" ]
How do I unit test HTTP Digest Authentication in Flask?
38,925,016
<p>I've got a flask app that implements a REST api. For reasons, I'm using HTTP Digest Authentication. I've used the Flask-HTTPAuth library to implement the digest authentication and it works; however, I am unable to authenticate in the unit tests. </p> <p>For the unit tests, prior to setting up the authentication, I'...
2
2016-08-12T19:14:18Z
38,927,799
<p>Unfortunately digest authentication is harder to test or bypass in Flask-HTTPAuth.</p> <p>One option is to actually calculate the correct hashes and perform the full authentication during tests. You can see a few examples of this in the <a href="https://github.com/miguelgrinberg/Flask-HTTPAuth/tree/master/tests" re...
2
2016-08-12T23:40:16Z
[ "python", "flask", "python-unittest", "digest-authentication", "flask-httpauth" ]
how to compare two columns in pandas to make a third column ?
38,925,082
<p>i have two columns age and sex in a pandas dataframe </p> <pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] </code></pre> <p>now i want to extract a third column : like this if age &lt;=9 then output ' child' and if age >9 then output the respective gender </p> <p...
2
2016-08-12T19:18:43Z
38,925,156
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p> <pre><code>df['col3'] = np.where(df['age'] &lt;= 9, 'child', df['sex']) </code></pre> <p>The resulting output:</p> <pre><code> age sex col3 0 16 m m 1 15 f f 2 ...
6
2016-08-12T19:23:50Z
[ "python", "pandas" ]
how to compare two columns in pandas to make a third column ?
38,925,082
<p>i have two columns age and sex in a pandas dataframe </p> <pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] </code></pre> <p>now i want to extract a third column : like this if age &lt;=9 then output ' child' and if age >9 then output the respective gender </p> <p...
2
2016-08-12T19:18:43Z
38,925,166
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow">pandas.DataFrame.where</a>. For example</p> <pre><code>child.where(age&lt;=9, sex) </code></pre>
4
2016-08-12T19:24:12Z
[ "python", "pandas" ]
how to compare two columns in pandas to make a third column ?
38,925,082
<p>i have two columns age and sex in a pandas dataframe </p> <pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] </code></pre> <p>now i want to extract a third column : like this if age &lt;=9 then output ' child' and if age >9 then output the respective gender </p> <p...
2
2016-08-12T19:18:43Z
38,925,236
<pre><code>df = pd.DataFrame({'sex':['m', 'f' , 'm', 'f', 'f', 'f', 'f'], 'age':[16, 15, 14, 9, 8, 2, 56]}) df['yes'] = df.apply(lambda x: 'child' if x['age'] &lt;= 9 else x['sex'], axis=1) </code></pre> <p>Result:</p> <pre><code> age sex yes 0 16 m m 1 15 f f 2 14 m m 3 9 f ...
1
2016-08-12T19:29:10Z
[ "python", "pandas" ]
IPython Notebook: Count number of cells in notebook
38,925,125
<p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p> <p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
3
2016-08-12T19:21:48Z
38,925,464
<ol> <li>I recommend you don't use the same ipython notebook for everything. If using multiple notebooks would lead to repeat code, you should be able to factor out common functionality into actual python modules which your notebooks can import.</li> <li>the notebook is just a json file, if you read the file as a json ...
5
2016-08-12T19:46:50Z
[ "python", "ipython", "ipython-notebook", "jupyter-notebook" ]
IPython Notebook: Count number of cells in notebook
38,925,125
<p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p> <p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
3
2016-08-12T19:21:48Z
38,925,503
<p>You could execute your notebook from the command line by:</p> <pre><code>jupyter nbconvert --ExecutePreprocessor.allow_errors=True --to notebook --execute jupyter_notebook.ipynb </code></pre> <p>where: <code>jupyter_notebook.ipynb</code> should be replaced with your <code>filename.ipynb</code>.</p> <p>With <code>...
1
2016-08-12T19:48:44Z
[ "python", "ipython", "ipython-notebook", "jupyter-notebook" ]
IPython Notebook: Count number of cells in notebook
38,925,125
<p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p> <p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
3
2016-08-12T19:21:48Z
38,926,044
<p>There's actually no need to parse the json. Just read it as text and count instances of, for example, "cell type":</p> <pre><code>with open(fname, 'r') as f: counter = 0 for line in f: if '"cell_type":' in line: counter += 1 </code></pre> <p>Or, even easier, <strong>just open your .ipy...
3
2016-08-12T20:31:46Z
[ "python", "ipython", "ipython-notebook", "jupyter-notebook" ]
handling a sequence of pyparsing expressions in any order and number
38,925,138
<p>Using pyparsing, I need to specify that two expressions can occur in any order and in any number between two braces. Below is my code. </p> <pre><code>import pyparsing as pp def updateList(someList): def parseAction(str, loc, tokens): someList.append(tokens[0]) return parseAction msgNameList = [] ...
1
2016-08-12T19:22:21Z
38,925,426
<p>(First, in the future, please prepare a <a href="http://stackoverflow.com/help/mcve">MCVE</a> of your question. The gist of your question is</p> <blockquote> <p>Using pyparsing, I need to specify that two expressions can occur in any order and in any number between two braces. Below is my code. </p> </blockquote>...
2
2016-08-12T19:43:41Z
[ "python", "python-2.7", "parsing", "pyparsing" ]
Redshift Python UDFs Import on Every Function Call
38,925,245
<p>I'm starting to learn Python User-Defined Functions in Redshift and I have a couple of questions that I would need clarifications on. Assuming that I have defined the following function:</p> <pre><code>CREATE OR REPLACE FUNCTION f_parse_url_query_string(url VARCHAR(MAX)) RETURNS varchar(max) STABLE AS $$ from u...
1
2016-08-12T19:29:44Z
38,928,574
<p><strong>Execution</strong></p> <p>Yes, the <code>import</code> will execute every time.</p> <p>One way to avoid this is to use <code>IMMUTABLE</code> as the volatility of the function. This allows Redshift to cache the output of the function for the given input value, avoiding the need to run the Python function i...
1
2016-08-13T02:16:41Z
[ "python", "user-defined-functions", "amazon-redshift" ]
Django manage.py runserver do not display "Welcome Page"
38,925,323
<p>I am following the Django Tutorial but I am getting a error when trying to load the welcome page, just after starting the server I did this tutorial in other pc and I did not have any problem. </p> <p>Using: Windows 7 / Djando 1.9 / Python 3.4.5</p> <p>1 - I started the project 2 - python manage.py runserver <a h...
0
2016-08-12T19:35:45Z
38,926,890
<p>The problem is, you have no router or view defined for "/". All valid paths would be <a href="http://127.0.0.1/polls/" rel="nofollow">http://127.0.0.1/polls/</a>* and <a href="http://127.0.0.1/admin/" rel="nofollow">http://127.0.0.1/admin/</a>*.</p> <pre><code>from django.conf.urls import include, url from django.c...
0
2016-08-12T21:45:47Z
[ "python", "django", "django-admin", "django-manage.py" ]
Pyspark Enforce Nullability on Read of Json File
38,925,358
<p>I'm trying to read a json file and enforce a schema on read using SQLContext but the nullability part seems to get ignored. I have a schema something like this:</p> <pre><code>StructType(List(StructField(some_field,StringType,false), StructField(some_other_field,StringType,false)) </code></pre> <p>Now then, I wan...
1
2016-08-12T19:38:44Z
38,956,571
<p>According to the research I've found, this is a bug in Spark that did not get resolved until Spark 2.0.0. I would love if someone who is using Spark 2.0.0 or higher could confirm this bug is fixed, but until then, here is the Apache Jira ticket discussing the issue:</p> <p><a href="https://issues.apache.org/jira/br...
0
2016-08-15T14:02:14Z
[ "python", "pyspark", "nullable" ]
Remove double quotes in table name during SQLAlchemy code execution (Teradata)
38,925,364
<p>I'm trying to write a basic ORM SQLAlchemy class to access a Teradata table. However, when SQLAlchemy creates and executes the SQL code, it puts my table name in double quotes, which prevents Teradata from recognizing the table as a valid table name (it's expecting the table name without quotes). Is there anyway to ...
0
2016-08-12T19:39:23Z
38,925,589
<p><code>dbo</code> is not part of the table's name; it's the schema name of the table. The way to specify the schema in SQLAlchemy is like this:</p> <pre><code>class d_game_info(Base): __table_args__ = {'schema' : 'dbo'} </code></pre>
0
2016-08-12T19:55:49Z
[ "python", "sql", "sqlalchemy", "teradata" ]
Hubspot (Jinja): Adding variables to blog data for output in for loop
38,925,456
<p><em>Hubspot is built in jinja and provides a limited and customized jinja library for use by it's developers. no server side access is available and python does not work in it's templates</em> </p> <p>Hello,</p> <p>I am wondering if it is possible to add variables to the blog data.</p> <p>Currently to build out a...
0
2016-08-12T19:46:10Z
38,925,785
<p>I answered my own question.</p> <p>I used the developer info (I had to use a code beautifier and the in page search) but I found the choice widget within the data for each post.</p> <p>I was expecting it to be something like</p> <pre><code>{{ content.widget_data.foo.value }} </code></pre> <p>as this is how it wo...
0
2016-08-12T20:11:30Z
[ "python", "templates", "jinja2", "hubspot" ]
Easy Way To Convert A List To A String, Still Formatted As A List
38,925,519
<p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p> <p>In Python 3, how can you convert a list, such as</p> <pre><code>['hello','world'] </code></pre> <p>to a string that is formatted exactly the same, like</p> <pre><code>"['hello','world']" </code></pre> <p>I...
0
2016-08-12T19:50:14Z
38,925,555
<p>Just simply say:</p> <pre><code>lst = ['hello', 'world'] new_str = str(lst) print(new_str) # prints out ["hello", "world"] </code></pre> <p>Python won't just convert the string to string format unless your explicitly tell it to. Like so:</p> <pre><code>lst = ['hello', 'world'] str1 = str(''.join(lst)) print(str1)...
1
2016-08-12T19:52:45Z
[ "python", "string", "list", "data-type-conversion" ]
Easy Way To Convert A List To A String, Still Formatted As A List
38,925,519
<p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p> <p>In Python 3, how can you convert a list, such as</p> <pre><code>['hello','world'] </code></pre> <p>to a string that is formatted exactly the same, like</p> <pre><code>"['hello','world']" </code></pre> <p>I...
0
2016-08-12T19:50:14Z
38,925,708
<p>Short answer is: You can't do exactly what you're asking.</p> <p>You cannot take any list that you typed in Python and get a string with the exact same original formatting. Python is pretty lenient with spacing within lists, so you can construct lists as such:</p> <ol> <li><code>['hello', 'world']</code></li> <li>...
0
2016-08-12T20:05:13Z
[ "python", "string", "list", "data-type-conversion" ]
Easy Way To Convert A List To A String, Still Formatted As A List
38,925,519
<p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p> <p>In Python 3, how can you convert a list, such as</p> <pre><code>['hello','world'] </code></pre> <p>to a string that is formatted exactly the same, like</p> <pre><code>"['hello','world']" </code></pre> <p>I...
0
2016-08-12T19:50:14Z
38,925,746
<p>Both a lists <code>str()</code> and <code>repr()</code> forms are what you are asking for, assuming that the it is a list of simple strings.<br> If you have a more complicated structure and wish to transfer (serialize) to string form and back to object form you may want to look into the <code>json</code> module:</p>...
1
2016-08-12T20:08:25Z
[ "python", "string", "list", "data-type-conversion" ]
how to choose status within all name in noSQL (MongoDB)
38,925,537
<p>I have this JSON type document</p> <pre><code>{ "user": { "honza": { "email": "haha", "telephone": "5454", "status": "online" }, "sara": { "email": "sdfsdf", "telephone": "656", "status": "online" }, ...
-1
2016-08-12T19:51:42Z
38,926,284
<p>You might consider using <strong>elemMatch</strong> in your query. </p> <p><a href="https://docs.mongodb.com/manual/reference/operator/query/elemMatch/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/query/elemMatch/</a></p>
1
2016-08-12T20:51:46Z
[ "python", "arrays", "json", "mongodb", "nosql" ]
Concat/merge xr.DataArray along an existing axis (Xarray | Python 3)
38,925,559
<p>Here is a toy example but I have 2 dataframes; (1) rows=samples, cols=attributes; and (2) rows=samples, cols=metadata-fields.</p> <p>I want to <code>concat</code> or <code>merge</code> to create 3-dimensional <code>xr.DataArray</code>. I've done this multiple times but I can't figure out why it's not working in th...
1
2016-08-12T19:53:11Z
38,949,242
<p>You can't (yet) concatenate DataArrays with different dimensions. You need to broadcast them explicitly first, e.g.,</p> <pre><code>In [38]: xr.concat(xr.broadcast(DA_A, DA_B), dim="patient_id") Out[38]: &lt;xarray.DataArray (patient_id: 84, attribute: 481, metadata: 32)&gt; array([[[ 0.5488135 , 0.5488135 , 0.54...
1
2016-08-15T04:14:02Z
[ "python", "pandas", "python-xarray" ]
Python chrs not showing properly
38,925,560
<p>When i have a string that has something like <code>"Hi \\x00"</code> and when i try and use something like</p> <pre><code>thatstring = thatstring.replace("\\x00",chr(0)) </code></pre> <p>and then save it to a file</p> <pre><code>f = open("test.txt","r+") f.seek(0) f.write(thatstring) f.truncate() f.close() </code...
1
2016-08-12T19:53:12Z
38,925,718
<p>Your text in the file is a <em>literal</em> <code>\\x00</code>, so <strong>two</strong> backslashes. Your code then only replaces <strong>one</strong> of those backslashes:</p> <pre><code>&gt;&gt;&gt; filecontents = r'Hi \\x00' # raw string literal to disable escape sequences &gt;&gt;&gt; list(filecontents.partiti...
2
2016-08-12T20:05:53Z
[ "python", "python-3.x" ]
How to read specific fields from binary file using numpy?
38,925,587
<p>I have a binary file that I am reading containing an array of a data type: </p> <pre><code>dt_particles = np.dtype([('id', np.int64), \ ('x', np.float32), \ ('y', np.float32), \ ('z', np.float32), \ ('vx', np.float3...
0
2016-08-12T19:55:48Z
38,925,894
<p>I haven't used <code>fromfile</code> much, but I doubt if it is possible to read selected fields. Clearly it is using the <code>dtype</code> to determine the layout and spacing of the elements. There's no parameter like <code>usecols</code> in <code>genfromtxt</code> to read selected fields or columns. And no way...
0
2016-08-12T20:19:42Z
[ "python", "numpy", "file-io" ]
Is it possible to run the asyncio.Server instance while the event loop is already running
38,925,616
<p>I'm trying to understand, is it possible to run the <code>asyncio.Server</code> instance while the event loop is already running by <code>run_forever</code> method (from a separate thread, of course). As I understand, the server can be started either by <code>loop.run_until_complete(asyncio.start_server(...))</code...
2
2016-08-12T19:57:57Z
38,939,903
<p>For communicating between event loop executed in one thread and conventional old good threaded code executed in other thread you might use <a href="https://github.com/aio-libs/janus" rel="nofollow">janus</a> library.</p> <p>It's a queue with two interfaces: async and thread-safe sync one.</p> <p>This is usage exam...
1
2016-08-14T06:54:22Z
[ "python", "python-asyncio" ]
command error after start project in django
38,925,638
<p>After upgrading my django from 1.8 to 1.10, when i start a project(django-admin startproject lwc) there is an error:</p> <p><code>CommandError: C:\Python34\binesh\lwc\lwc\settings.py already exists,</code> overlaying a project or app into an existing directory won't replace conflicting files. it creates a file for ...
2
2016-08-12T19:59:37Z
38,926,190
<p>You might have Django installed twice. Running "pip uninstall django" twice, and then reinstalling new version again should help.</p>
0
2016-08-12T20:43:38Z
[ "python", "django-upgrade" ]
command error after start project in django
38,925,638
<p>After upgrading my django from 1.8 to 1.10, when i start a project(django-admin startproject lwc) there is an error:</p> <p><code>CommandError: C:\Python34\binesh\lwc\lwc\settings.py already exists,</code> overlaying a project or app into an existing directory won't replace conflicting files. it creates a file for ...
2
2016-08-12T19:59:37Z
39,836,064
<p>Uninstall django, delete your python/Lib/site-packages/django directory completely, then reinstall.</p> <p>The installation of the new version, even though it claims to uninstall the old version, leaves old files hanging around, and they are quietly brought into the new version in various ways (e.g., manage.py can...
0
2016-10-03T16:18:54Z
[ "python", "django-upgrade" ]
flask-security roles_required with pluggable views
38,925,644
<p>I'm trying to require a role to access a view that I've defined as a MethodView. However, I can't seem to get the route to be named correctly.</p> <p>If I simply require logging in with a decorator everything works:</p> <pre><code>activities = Blueprint("activities", __name__, url_prefix="/activities") class Acti...
0
2016-08-12T19:59:49Z
39,005,060
<p>The solution is to call the decorator:</p> <pre><code>view = roles_required("experimenter")(ActivitiesView.as_view("activities")) activities.add_url_rule('/', view_func=view) </code></pre> <p>Alternatively:</p> <pre><code>decorators = [roles_required("experimenter")] </code></pre> <p>Thanks to this article:</p> ...
0
2016-08-17T19:45:03Z
[ "python", "flask", "flask-security" ]
Nested for-loop the pythonic way to structure data?
38,925,775
<p>I have structured data in some sources and ultimately I would like to step through each source, by the same amount, but starting at different indexes, in order to re-structure the data. </p> <p>I will go on to perform analysis on each item contained in each iterated slice of source. What is the python way to do thi...
2
2016-08-12T20:11:00Z
38,925,851
<p>A nested for loop with <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow"><code>slice</code></a> is a good starting point:</p> <pre><code>sources = [source1, source2, source3] slices = [slice(1,None,5), slice(2,None,5), slice(3,None,5)] for source in sources: for s in slices: ...
1
2016-08-12T20:16:14Z
[ "python", "nested-loops" ]
Nested for-loop the pythonic way to structure data?
38,925,775
<p>I have structured data in some sources and ultimately I would like to step through each source, by the same amount, but starting at different indexes, in order to re-structure the data. </p> <p>I will go on to perform analysis on each item contained in each iterated slice of source. What is the python way to do thi...
2
2016-08-12T20:11:00Z
38,926,394
<p>I'm sure there is a better way of doing what you need, but we're going to need give up more information. What are you going to do with your <em>iteratedSlice</em> variable? </p> <pre><code>sources = ('source1', 'source2' 'source3') for source in sources: for n in range(1, 4): iteratedSlice = source[n:5...
0
2016-08-12T21:00:36Z
[ "python", "nested-loops" ]
Can't get stdout/stderr from (Python) subprocess.check_output()
38,925,806
<p>I'm trying to get the message from a <code>git add</code> command, to print to a log file later on.</p> <pre><code>import subprocess import os filename = 'test.txt' # Add changes add_cmd = """git add "%s" """ % filename os.system(add_cmd) a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT) ...
0
2016-08-12T20:12:45Z
38,925,818
<p>From the documenation for <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a>:</p> <blockquote> <p>If the return code was non-zero it raises a <code>CalledProcessError</code>. The <code>CalledProcessError</code> object will ...
3
2016-08-12T20:13:54Z
[ "python", "git", "subprocess", "stdout", "stderr" ]
How do i declare more than one extra-index-url in pip.conf
38,925,928
<p>Where would I set this in pip.conf?</p> <p>I want to add two(2) extra-index-urls in pip.conf, but I did not find a solution how to do this after some research in the docs.</p>
1
2016-08-12T20:22:39Z
39,085,648
<p>Although the example in <a href="https://pip.pypa.io/en/stable/user_guide/#config-file" rel="nofollow">the docs</a> is for <code>--find-links</code>, it says: </p> <blockquote> <p>Appending options like <code>--find-links</code> can be written on multiple lines:</p> </blockquote> <pre><code>[global] find-links =...
0
2016-08-22T17:43:56Z
[ "python", "pip" ]
How to add lines together from two different paragraphs?
38,925,959
<p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p> <p>Something like this:</p> <p>Input 1:</p> <pre class="lan...
-4
2016-08-12T20:25:49Z
38,926,054
<p>How's this? </p> <pre><code>input1 = """ this is an example line that is a run on sentence """ input2 = """ i am another example paragraph that is very similar """ input1_lines = input1.strip().splitlines() input2_lines = input2.strip().splitlines() for line1, line2 in zip(input1_lines, input2_lines): prin...
1
2016-08-12T20:32:27Z
[ "python", "loops", "for-loop", "input" ]
How to add lines together from two different paragraphs?
38,925,959
<p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p> <p>Something like this:</p> <p>Input 1:</p> <pre class="lan...
-4
2016-08-12T20:25:49Z
38,926,089
<p>I know I'm late already, but here's another method:</p> <pre><code>a = """ this is an example line that is a run on sentence""" b = '''i am another example paragraph that is very similar''' a_list = a.split("\n") b_list = b.split("\n") c = [[x, b_list[index]] for index, x in enumerate(a_list)] c_string = "...
1
2016-08-12T20:35:16Z
[ "python", "loops", "for-loop", "input" ]
How to add lines together from two different paragraphs?
38,925,959
<p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p> <p>Something like this:</p> <p>Input 1:</p> <pre class="lan...
-4
2016-08-12T20:25:49Z
38,926,242
<p>The thing about izip is, what is the output of:</p> <pre><code>input1 = """ this is an example line that is a run """ input2 = """ i am another example paragraph that is on sentence """ input1_lines = input1.strip().splitlines() input2_lines = input2.strip().splitlines() for line1, line2 in zip(input1_lines, inp...
1
2016-08-12T20:48:22Z
[ "python", "loops", "for-loop", "input" ]
How to add lines together from two different paragraphs?
38,925,959
<p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p> <p>Something like this:</p> <p>Input 1:</p> <pre class="lan...
-4
2016-08-12T20:25:49Z
38,926,272
<p>You can use the string module functions. string.splitlines creates a list separated by newlines. The string.join function joins elements in a list by whatever characters come before the dot. For example:</p> <pre><code>import string lyric1 = """this is an example line that is a run on sentence""" lyric2 = """...
1
2016-08-12T20:50:32Z
[ "python", "loops", "for-loop", "input" ]
How to add lines together from two different paragraphs?
38,925,959
<p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p> <p>Something like this:</p> <p>Input 1:</p> <pre class="lan...
-4
2016-08-12T20:25:49Z
38,926,279
<p>First, you need to enter data into program. You may use <code>input()</code> function to enter single line, if you need more you may create you own <code>inp()</code> function based on standard <code>input</code>. Like so:</p> <pre><code> def inp(): res = [] line = input() while line != '...
1
2016-08-12T20:51:17Z
[ "python", "loops", "for-loop", "input" ]