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
Defining functions for multiple data sets
39,839,029
<p>I have bunch of data sets and their names are like;</p> <pre><code>df_a df_b df_c df_d ... </code></pre> <p>All the data sets have the same columns, My question is, I want to apply some functions all the data sets.</p> <p>The functions are like:</p> <pre><code>df.fillna(0, inplace=True) df['day_of_week'] = df.date.map(lambda x: x.strftime("%A")) </code></pre> <p>But I don't want to write these and another functions for all data sets separately. Is there any solution for for writing these functions in short cut for all data frames?</p>
0
2016-10-03T19:29:35Z
39,839,128
<pre><code>dfs = [df_a, df_b, ...] for dataset in dfs: do_thing(dataset) </code></pre>
0
2016-10-03T19:36:10Z
[ "python", "function", "pandas" ]
haskell, figuring use some defined function to draw the mandelbrot, need explanation
39,839,033
<p>I've write several function that need to used in function mandelbrot to draw it, here are these:</p> <pre><code># sp that takes integer n, element y, list xs. insert the specified element y after every n elements. sp 1 'a' ['b','c','d'] = ['b','a','c','a','d','a'] # plane that gives (x/r,y/r) where x and y are int, -2&lt;x/r&lt;1,-1&lt;y/r&lt;1. plane 1 = [(-2.0,-1.0),(-1.0,-1.0),(0.0,-1.0),(1.0,-1.0),(-2.0,0.0),(-1.0,0.0),(0.0,0.0),(1.0,0.0),(-2.0,1.0),(-1.0,1.0),(0.0,1.0),(1.0,1.0)] </code></pre> <p># orbit, is the same in this question : <a href="http://stackoverflow.com/questions/39809592/haskell-infinite-recursion-in-list-comprehension">Haskell infinite recursion in list comprehension</a></p> <pre><code>print(take 3 (orbit(2,1))) = [(2,1),(5,5),(2,51)] </code></pre> <p># find, is the same in this questionL <a href="http://stackoverflow.com/questions/39823833/haskell-recursive-function-that-return-the-char-in-a-tuple-list-with-certain-co">haskell: recursive function that return the char in a tuple list with certain condition(compare)</a></p> <pre><code>print(find 0.4 [(0.15,'#'),(0.5,'x'),(1,'.')]) == 'x' ## &gt;all will print char ' ' </code></pre> <p>So I'm trying to use sp,plane,orbit,and find,this four function with a new func named norm, that calculate the distances of points from the origin:</p> <pre><code>norm (x,y) = x*x + y*y </code></pre> <h2>Now is my question:</h2> <p>I'm little confused about what should do and why that, so I think I will first use plane to all the points, then use orbit to print the list with the point? And after this, what should I do? Can anyone explain these relationship of each function and what I should do?</p> <p>Separate code or explanation are fine. The mandelbrot function should draw something that looks like mandelbrot contains '#' 'x' '.' and ' '.</p>
0
2016-10-03T19:29:46Z
39,883,645
<p>I figure it out.</p> <p>So what I need to do is:</p> <pre><code>-- find all points using plane r -- using orbit list comprehension to take the orbit with one point at index i -- using norm(x,y) to calculate the distance of orbit to the original -- using find to give the list of char -- finally using sp to put character with 'n' -- all these stuff can using the list comprehension combine together. </code></pre> <p>Just for anyone who want to know how to solve this.</p>
0
2016-10-05T21:04:07Z
[ "python", "python-3.x", "haskell", "mandelbrot" ]
Python, tuple indices must be integers, not tuple?
39,839,034
<p>So, I'm not entirely sure what's going on here, but for whatever reason Python is throwing this at me. For reference, it's part of a small neural network I'm building for fun, but it uses a lot of np.array and such, so there's a lot of matrices being thrown around, so I think it's creating some sort of data type clash. Maybe somebody can help me figure this out, because I've been staring at this error for too long without being able to fix it.</p> <pre><code>#cross-entropy error #y is a vector of size N and output is an Nx3 array def CalculateError(self, output, y): #calculate total error against the vector y for the neurons where output = 1 (the rest are 0) totalError = 0 for i in range(0,len(y)): totalError += -np.log(output[i, int(y[i])]) #error is thrown here #now account for regularizer totalError+=(self.regLambda/self.inputDim) * (np.sum(np.square(self.W1))+np.sum(np.square(self.W2))) error=totalError/len(y) #divide ny N return error </code></pre> <p>EDIT: Here's the function that returns the output so you know where that came from. y is a vector of length 150 that is taken directly from a text document. at each index of y it contains an index either 1,2, or 3:</p> <pre><code>#forward propogation algorithm takes a matrix "X" of size 150 x 3 def ForProp(self, X): #signal vector for hidden layer #tanh activation function S1 = X.dot(self.W1) + self.b1 Z1 = np.tanh(S1) #vector for the final output layer S2 = Z1.dot(self.W2)+ self.b2 #softmax for output layer activation expScores = np.exp(S2) output = expScores/(np.sum(expScores, axis=1, keepdims=True)) return output,Z1 </code></pre>
0
2016-10-03T19:29:49Z
39,839,092
<p>Your <code>output</code> variable is not a <code>N x 4</code> matrix, at least not in <strong>python types</strong> sense. It is a <strong>tuple</strong>, which can only be indexed by a single number, and you try to index by tuple (2 numbers with coma in between), which works only for numpy matrices. Print your output, figure out if the problem is just a type (then just convert to np.array) or if you are passing something completely different (then fix whatever is producing <code>output</code>).</p> <p>Example of what is happening:</p> <pre><code>import numpy as np output = ((1,2,3,5), (1,2,1,1)) print output[1, 2] # your error print output[(1, 2)] # your error as well - these are equivalent calls print output[1][2] # ok print np.array(output)[1, 2] # ok print np.array(output)[(1, 2)] # ok print np.array(output)[1][2] # ok </code></pre>
3
2016-10-03T19:33:47Z
[ "python", "indexing", "types", "tuples" ]
Script for extracting information of specific pattern from a text file
39,839,065
<p>Hi I am working on a project which deals with large amount of data. I have a text file of around 2 GB with key value pairs and each key has multiple values. I need to extract all the keys in a different file, as I need the keys for testing a particular feature.</p> <p>The format of the file is:</p> <pre><code>:k: k1 :v: {XYZ:{id:"k1",score:0e0,tags:null},ABC:[{XYZ:{id:"k1",score:0e0,tags:null},PQR:[{id:"ID1",score:71.85e0,tags:[{color:"DARK"},{Type:"S1"},{color:"BLACK"}]},MetaData:{RuleId:"R3",Score:66.26327129015809e0,Quality:"GOOD"}},{XYZ:{id:"k1",score:0e0,tags:null},PQR:[..(same as above format)..],MetaData:{RuleId:"R3",Score:65.8234565409752e0,Quality:"GOOD"}} :: //same pattern repeats with different keys, and a new line </code></pre> <p>When I search ":k: " in the file using CTRL+F, these keys only get highlighted. SO I think this kind of pattern is no where in the file except the start of the line</p> <p>Like these there are thousands of keys.</p> <p>And I want all these keys (k1, k2) extracted to a separate file for testing.</p> <p>There are multiple lines for :k: and want to separate (k1, k2, ..) in a separate file. How can I do this?</p> <p>Python is also fine for me. I can use regular expressions in python or maybe use "sed" shell command. Please help me out here how I can use these to extract the keys.</p> <p>Can someone help me in writing a shell/python script for same. I know its very trivial but I'm novice to all this kind of data processing.</p> <p>Also focusing on optimizing the run time, as the data is very large.</p>
-2
2016-10-03T19:31:57Z
39,852,319
<p>Assuming a file like</p> <pre><code>:k: k1 :v: {XYZ:{id: :k2: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: :k3: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: </code></pre> <p>You can easily do (in 1 pass), and with no memory restrictions</p> <pre><code>awk '{fName=$1; gsub(/:/,"",fName); print &gt;&gt; fName ; close(fName)}' inFile </code></pre> <p>which gives the following output</p> <pre><code>$ cat k :k: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: $ cat k2 :k2: k1 :v: {XYZ:{id: $ cat k3 :k3: k1 :v: {XYZ:{id: </code></pre> <p>Depending on how may keys you have, you may not need the <code>close(fName)</code>, but if you don't want to spend time testing what your limit of open files are, then this is the safe way to do the process.</p> <p>IHTH</p>
0
2016-10-04T12:26:05Z
[ "python", "bash", "shell", "pattern-matching", "data-processing" ]
How to process a date diference using same id elements in a list
39,839,067
<p><strong>I have the following data structure:</strong></p> <pre><code>[ (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)), (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)), (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)), (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)), (80L, datetime.datetime(2014, 9, 15, 14, 16, 39)), (80L, datetime.datetime(2014, 2, 6, 8, 58, 39)), (80L, datetime.datetime(2014, 9, 8, 14, 21, 48)), (90L, datetime.datetime(2016, 8, 2, 18, 14, 31)), (90L, datetime.datetime(2016, 8, 2, 21, 14, 23)), (90L, datetime.datetime(2014, 1, 5, 16, 35, 34)) ] </code></pre> <p>And i need to calculate the average days between the days from users with same id, first element corresponds to user id's and the second one to a datetime.</p> <p>I'm getting trouble on how to iterate through the list, counting and getting the same diff for each user...</p>
0
2016-10-03T19:32:07Z
39,839,232
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> to group by user id (assuming the list is sorted by the grouping key - which looks like it is), then, you can use "pairwise" iteration and calculate an average day difference:</p> <pre><code>In [1]: import datetime In [2]: from operator import itemgetter In [3]: from itertools import groupby, combinations In [4]: l = [ ...: (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)), ...: (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)), ...: (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)), ...: (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)), ...: (80L, datetime.datetime(2014, 9, 15, 14, 16, 39)), ...: (80L, datetime.datetime(2014, 2, 6, 8, 58, 39)), ...: (80L, datetime.datetime(2014, 9, 8, 14, 21, 48)), ...: (90L, datetime.datetime(2016, 8, 2, 18, 14, 31)), ...: (90L, datetime.datetime(2016, 8, 2, 21, 14, 23)), ...: (90L, datetime.datetime(2014, 1, 5, 16, 35, 34)) ] In [5]: for user_id, dates in groupby(l, itemgetter(0)): ...: dates = [date[1] for date in dates] ...: differences = [abs((d1 - d2).days) for d1, d2 in zip(dates[0::2], dates[1::2])] ...: print(user_id, sum(differences) / len(differences)) ...: (19L, 2) (80L, 108) (90L, 1) </code></pre>
0
2016-10-03T19:43:38Z
[ "python", "list", "loops", "counting" ]
How to process a date diference using same id elements in a list
39,839,067
<p><strong>I have the following data structure:</strong></p> <pre><code>[ (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)), (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)), (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)), (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)), (80L, datetime.datetime(2014, 9, 15, 14, 16, 39)), (80L, datetime.datetime(2014, 2, 6, 8, 58, 39)), (80L, datetime.datetime(2014, 9, 8, 14, 21, 48)), (90L, datetime.datetime(2016, 8, 2, 18, 14, 31)), (90L, datetime.datetime(2016, 8, 2, 21, 14, 23)), (90L, datetime.datetime(2014, 1, 5, 16, 35, 34)) ] </code></pre> <p>And i need to calculate the average days between the days from users with same id, first element corresponds to user id's and the second one to a datetime.</p> <p>I'm getting trouble on how to iterate through the list, counting and getting the same diff for each user...</p>
0
2016-10-03T19:32:07Z
39,839,357
<p>I would sort the timestamps into a dictionary where each key is a user's ID and the value is a list of access times. then after sorting that list of timestamps, find the difference between each visit time and find the average. the <code>datetime.timedelta</code> object can be used to simplify math operations on timestamps..</p> <pre class="lang-python prettyprint-override"><code>from collections import defaultdict from datetime import datetime #l = [(id, datetime), (...), ...] d = defaultdict(list) for ID, time in l: d[ID].append(time) # build list of times from timestamps d[ID].sort() # sorting every time is not optimal but functional for ID in d.keys(): timeDeltas = [d[ID][i+1] - d[ID][i] for i in range(len(d[ID])-1)] # create list of timedeltas averageVisitFrequency = reduce(lambda x,y: x+y, timeDeltas)//len(timeDeltas) # calculate average timedelta print 'user {} makes a purchase every {} days on average'.format(ID, averageVisitFrequency.days) # example output usage</code></pre>
-1
2016-10-03T19:52:27Z
[ "python", "list", "loops", "counting" ]
Python Celery - Permission Issue - Unable to upload files from a download task
39,839,084
<p>I have a Celery task whose job is to download files to a local directory, and then upload to a S3 bucket when download is complete.</p> <p>My issue is that with a recent update of the workers, I'm getting permission denied errors when accessing the folder to upload. The code was fundamentally unchanged other than from going to script-method to class based implementation.</p> <p>I made a task just to create the directories, with a single method call:</p> <pre><code>os.mkdirs(path, 777) </code></pre> <p>and it creates the directory with permissions <code>300</code></p> <p>This is despite </p> <pre><code>CELERYD_USERS='ubuntu' CELERYD_GROUP='ubuntu' CELERYD_CREATE_DIRS=1 </code></pre> <p>in the config.</p> <p>According to the <a href="http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html#example-django-configuration" rel="nofollow">docs</a>, the last option allows celery to create a directory owned byt the user/group specified above. That much is happening, but nothing is said about <em>permissions</em>.</p> <p>Is there any way around this?</p>
0
2016-10-03T19:33:26Z
39,839,531
<p>The CELERY_CREATE_DIR only tells celery create its operational directories:</p> <blockquote> <p>Always create directories (log directory and pid file directory). Default is to only create directories when no custom logfile/pidfile set.</p> </blockquote> <p>I believe your problem is with the <code>os.mkdirs</code>. According to the <a href="https://docs.python.org/3/library/os.html#os.mkdir" rel="nofollow">os.mkdir doc</a>, <code>mode</code> may be ignored on your system and you need to use <code>os.chmod</code> to change the mode.</p>
0
2016-10-03T20:03:50Z
[ "python", "django", "celery" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this string. Then you sort them and find the index of <code>'xyz'</code> out of the unique permutations. Which seemed simple enough but then once you get a really long string, my computer gives up. What's the mathematical way around this which I'd assume would lead me to code that can actually run on my laptop.</p> <pre><code>from itertools import permutations def find_rank(n): perms = [''.join(p) for p in permutations(n)] perms = sorted(set(perms)) loc = perms.index(n) return loc </code></pre> <p>But if I want to run this code on a string that's 100 letters long, it's just way too many for my computer to handle. </p>
4
2016-10-03T19:35:32Z
39,839,283
<p>This problem can be easily solved by first simplifying it and thinking recursively.</p> <p>So let's first assume that all the elements in the input sequence are unique, then the set of "unique" permutations is simply the set of permutations.</p> <p>Now to find the rank of the sequence <code>a_1, a_2, a_3, ..., a_n</code> into its set of permutations we can:</p> <ol> <li><p>Sort the sequence to obtain <code>b_1, b_2, ..., b_n</code>. This permutation by definition has rank <code>0</code>.</p></li> <li><p>Now we compare <code>a_1</code> and <code>b_1</code>. If they are the same then we can simply remove them from the problem: the rank of <code>a_1, a_2, ..., a_n</code> will be the same as the rank of just <code>a_2, ..., a_n</code>.</p></li> <li><p>Otherwise <code>b_1 &lt; a_1</code>, but then <strong>all</strong> permutations that start with <code>b_1</code> are going to be smaller than <code>a_1, a_2, ..., a_n</code>. The number of such permutations is easy to compute, it's just <code>(n-1)! = (n-1)*(n-2)*(n-3)*...*1</code>.</p> <p>But then we can continue looking at our sequence <code>b_1, ..., b_n</code>. If <code>b_2 &lt; a_1</code>, again all permutations starting with <code>b_2</code> will be smaller. So we should add <code>(n-1)!</code> again to our rank.</p> <p>We do this until we find an index <code>j</code> where <code>b_j == a_j</code>, and then we end up at point 2.</p></li> </ol> <p>This can be implemented quite easily:</p> <pre><code>import math def permutation_rank(seq): ref = sorted(seq) if ref == seq: return 0 else: rank = 0 f = math.factorial(len(seq)-1) for x in ref: if x &lt; seq[0]: rank += f else: rank += permutation_rank(seq[1:]) if seq[1:] else 0 return rank </code></pre> <p>The solution is pretty fast:</p> <pre><code>In [24]: import string ...: import random ...: seq = list(string.ascii_lowercase) ...: random.shuffle(seq) ...: print(*seq) ...: print(permutation_rank(seq)) ...: r q n c d w s k a z b e m g u f i o l t j x p h y v 273956214557578232851005079 </code></pre> <p>On the issue of equal elements: the point where they come into play is that <code>(n-1)!</code> is the number of permutations, considering each element as different from the others. If you have a sequence of length <code>n</code>, made of symbol <code>s_1, ..., s_k</code> and symbol <code>s_j</code> appears <code>c_j</code> times then the number of unique permutations is `(n-1)! / (c_1! * c_2! * ... * c_k!).</p> <p>This means that instead of just adding <code>(n-1)!</code> we have to divide it by that number, and also we want to decrease by one the count <code>c_t</code> of the current symbol we are considering.</p> <p>This can be done in this way:</p> <pre><code>import math from collections import Counter from functools import reduce from operator import mul def permutation_rank(seq): ref = sorted(seq) counts = Counter(ref) if ref == seq: return 0 else: rank = 0 f = math.factorial(len(seq)-1) for x in sorted(set(ref)): if x &lt; seq[0]: counts_copy = counts.copy() counts_copy[x] -= 1 rank += f//(reduce(mul, (math.factorial(c) for c in counts_copy.values()), 1)) else: rank += permutation_rank(seq[1:]) if seq[1:] else 0 return rank </code></pre> <p>I'm pretty sure there is a way to avoid copying the counts dictionary, but right now I'm tired so I'll let that as an exercise for the reader.</p> <p>For reference, the final result:</p> <pre><code>In [44]: for i,x in enumerate(sorted(set(it.permutations('aabc')))): ...: print(i, x, permutation_rank(x)) ...: 0 ('a', 'a', 'b', 'c') 0 1 ('a', 'a', 'c', 'b') 1 2 ('a', 'b', 'a', 'c') 2 3 ('a', 'b', 'c', 'a') 3 4 ('a', 'c', 'a', 'b') 4 5 ('a', 'c', 'b', 'a') 5 6 ('b', 'a', 'a', 'c') 6 7 ('b', 'a', 'c', 'a') 7 8 ('b', 'c', 'a', 'a') 8 9 ('c', 'a', 'a', 'b') 9 10 ('c', 'a', 'b', 'a') 10 11 ('c', 'b', 'a', 'a') 11 </code></pre> <p>And to show that it is efficient:</p> <pre><code>In [45]: permutation_rank('zuibibzboofpaoibpaybfyab') Out[45]: 246218968687554178 </code></pre>
1
2016-10-03T19:46:38Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this string. Then you sort them and find the index of <code>'xyz'</code> out of the unique permutations. Which seemed simple enough but then once you get a really long string, my computer gives up. What's the mathematical way around this which I'd assume would lead me to code that can actually run on my laptop.</p> <pre><code>from itertools import permutations def find_rank(n): perms = [''.join(p) for p in permutations(n)] perms = sorted(set(perms)) loc = perms.index(n) return loc </code></pre> <p>But if I want to run this code on a string that's 100 letters long, it's just way too many for my computer to handle. </p>
4
2016-10-03T19:35:32Z
39,839,340
<p>Here's some Ruby code I wrote to do exactly this. You'd need to modify it if you have repeated elements (and decide how you want to handle them). </p> <p>This takes advantage that if we have n elements, each selection of k elements will show up exactly (n-k)! times. E.g., [a,b,c,d] -- if we look at all permutations, (4-1)! = 3! of them will start with each of 'a', 'b', 'c', and 'd'. In particular, the first 3! will start with 'a', the next 3! with b, and so on. Then you recurse on the remaining elts.</p> <pre><code> def get_perm_id(arr) arr_len = arr.length raise "get_perm_id requires an array of unique elts" if arr_len != arr.uniq.length arr_sorted = arr.sort perm_num = 0 0.upto(arr_len - 2) do |i| arr_elt = self[i] sorted_index = arr_sorted.find_index(arr_elt) sorted_right_index = arr_sorted.length - sorted_index - 1 right_index = arr_len - i - 1 left_delta = [0, right_index - sorted_right_index].max perm_num += left_delta * (arr_len - i - 1).factorial arr_sorted.slice!(sorted_index) end perm_num end </code></pre>
0
2016-10-03T19:51:16Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this string. Then you sort them and find the index of <code>'xyz'</code> out of the unique permutations. Which seemed simple enough but then once you get a really long string, my computer gives up. What's the mathematical way around this which I'd assume would lead me to code that can actually run on my laptop.</p> <pre><code>from itertools import permutations def find_rank(n): perms = [''.join(p) for p in permutations(n)] perms = sorted(set(perms)) loc = perms.index(n) return loc </code></pre> <p>But if I want to run this code on a string that's 100 letters long, it's just way too many for my computer to handle. </p>
4
2016-10-03T19:35:32Z
39,839,381
<p><strong>Let's see how index of string can be calculated without finding all permutation of the string.</strong> </p> <p>Consider string <code>s = "cdab".</code> Now, before string <code>s</code> (in lexical order), strings <code>"a***",</code> <code>"b***"</code> would be there. (<code>*</code> denotes remaining characters).</p> <p>That's <code>2*3!</code> strings. So any strings starting with <code>c</code> will have index more than this. </p> <p>After <code>"a***"</code> and <code>"b***",</code> string starting with <code>'c'</code>will begin. Index of the string <code>s = 2*3! + index("dab")</code>.</p> <p>Now recursively find the index for <code>"dab"</code></p> <p>Just for illustration, order of string goes as follows : </p> <pre><code> a*** --&gt; 3! b*** --&gt; 3! ca** --&gt; 2! cb** --&gt; 2! cdab --&gt; 1 </code></pre> <p>Following is the python code : </p> <pre><code>import math def index(s): if(len(s)==1): return 1 first_char = s[0] character_greater = 0 for c in s: if(first_char&gt;c): character_greater = character_greater+1 return (character_greater*math.factorial((len(s)-1)) + index(s[1:len(s)]) </code></pre>
0
2016-10-03T19:53:52Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
How to Define a Piecewise Function in Python with Multiple Variables
39,839,138
<p>I am trying to develop a plot for my helioseismology class and the question had provided a piecewise function describing the dynamics of the "fluids" in a star as if it is one thing its this and if its another its that. I am receiving over and over again this <code>'Mul' object cannot be interpreted as an integer</code> but I am working with numbers in the reals not just the integer set. I do not know how to get around this and need guidance. The code is as follows.</p> <pre><code>import sympy as sy from sympy import * from sympy.physics.units import Unit import numpy as np import sys import math import scipy as sp from scipy import special phi = Symbol('phi', Variable = True) x = Symbol('x', Variable = True, Real = True) t = Symbol('t', Variable = True, Real = True) xi = Symbol('xi', Function = True) Solar_Radius = Symbol('R', Constant = True, unit = "meters") Sound_Speed = Symbol('c', Constant = True, unit = "meters per second", Real = True) gamma = Symbol('gamma', Constant = True) gravity = Symbol('g', Constant = True, unit = "meters per second per second") Solar_Radius = 6.963 * 10 ** 6 gamma = 5/3 g = 274.8265625336 gas_constant = 8201.25 c = 8.1 * 10 ** 3 for t in range(0,x/c): xi[x,t] = 0 for t in range(x/c,00): xi[x,t] = (1/2)*sy.exp(gamma*g*x/(2*c**2))*mpmath.besselj(0, (gamma*g/(2*c)*sy.sqrt(t**2 - ((x/c)**2))),derivative = 0) </code></pre> <p>Full Traceback:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-50-3506376f1686&gt; in &lt;module&gt;() ----&gt; 1 for t in range(0,x/c): 2 xi[x,t] = 0 3 for t in range(x/c,00): 4 xi[x,t] = (1/2)*sy.exp(gamma*g*x/(2*c**2))*mpmath.besselj(0, (gamma*g/(2*c)*sy.sqrt(t**2 - ((x/c)**2))),derivative = 0) TypeError: 'Mul' object cannot be interpreted as an integer </code></pre>
1
2016-10-03T19:37:05Z
39,859,692
<p>There are quite a few issues here:</p> <ul> <li><p>None of the keyword arguments (Constant, Variable, unit, Real) that you are passing to Symbol are things that are recognized by SymPy. The only one that is close is <code>real</code>, which should be lowercase (like <code>Symbol('x', real=True)</code>). The rest do nothing. If you want units, you should use the SymPy units module in <code>sympy.physics.units</code>. There is no need to specify if a symbol is constant or variable. </p></li> <li><p>You have redefined <code>Solar_Radius</code> and <code>gamma</code> as numbers. That means that the Symbol definitions for those variables are pointless. </p></li> <li><p>If you are using Python 2, make sure to include <code>from __future__ import division</code> at the top of the file, or else things like <code>1/2</code> and <code>5/3</code> will be truncated with integer division (this isn't an issue in Python 3). </p></li> <li><p><code>range(0, x/c)</code> doesn't make sense. <code>range</code> creates a list of numbers, like <code>range(0, 3)</code> -> <code>[0, 1, 2]</code>. But <code>x/c</code> is not a number, it's a symbolic expression.</p></li> <li><p>Additionally, <code>xi[x, t] = ...</code> doesn't make sense. <code>xi</code> is a Symbol, which doesn't allow indexing and certainly doesn't allow assignment.</p></li> <li><p>Don't mix numeric (math, mpmath, numpy, scipy) functions with SymPy functions. They won't work with symbolic expressions. You should use only SymPy functions. If you create a symbolic expression and want to convert it to a numeric one (e.g., for plotting), use <code>lambdify</code>.</p></li> </ul> <p>What you want here is <code>Piecewise</code>. The syntax is <code>Piecewise((expr, cond), (expr, cond), ..., (expr, True))</code>, where <code>expr</code> is an expression that is used when <code>cond</code> is true (<code>(expr, True)</code> is the "otherwise" condition). </p> <p>For your example, I believe you want</p> <pre><code>expr = Piecewise((0, t &lt; x/c), (sy.exp(gamma*g*x/(2*c**2))*sy.besselj(0, (gamma*g/(2*c)*sy.sqrt(t**2 - (x/c)**2)))/2, t &gt;= x/c)) </code></pre> <p>If you want to turn this into a numeric function in <code>x</code> and <code>t</code>, use</p> <pre><code>xi = lambdify((x, t), expr) </code></pre>
1
2016-10-04T18:52:26Z
[ "python", "for-loop", "sympy", "bessel-functions" ]
The difference between applying permissions to separate object and list of objects in django rest framework
39,839,156
<p>In my code permissions result differently to object and list of objects.</p> <p>Let's say we have one model of <code>User</code>:</p> <pre><code>class User(auth.AbstractBaseUser, auth.PermissionsMixin): name = models.CharField(max_length=255, blank=True, null=True) profile_status = models.CharField(max_length=255, blank=True, null=True) </code></pre> <p>and two rows in db:</p> <pre><code>1. name = "Dennis", profile_status = "private" # (not "public") 2. name = "Robert", profile_status = "private" # (not "public") </code></pre> <p>and the viewset:</p> <pre><code>class UsersViewSet(viewsets.CreateListRetrieveUpdateViewSet): queryset = models.User.objects.all() # doesn't matter... serializer_class = serializers.UserSerializer # doesn't matter... filter_class = filters.UsersFilterSet # doesn't matter... permission_classes = [IsProfileAccessStatus('public'), IsReadOnly] </code></pre> <p><code>IsProfileAccessStatus('public')</code> django permission returns <code>True</code> if object's <code>profile_status</code> equals 'public':</p> <pre><code>def IsProfileAccessStatus(access_status=''): class IsProfileStatusOf(BasePermission): def has_object_permission(self, request, view, obj): return hasattr(obj, 'profile_status') and \ obj.profile_status== access_status return IsProfileStatusOf </code></pre> <p>Back end returns users at <code>/api/users/</code> and speicific one at <code>/api/users/:name/</code>.</p> <p><em>Different output</em></p> <p>On <code>/api/users/Dennis/</code> drf returns exception according the <code>IsProfileAccessStatus('public')</code> permission. So it's okay.</p> <p>But for <code>/api/users/</code> it returns both objects:</p> <pre><code>[ { "name": "Dennis", "profile_status": "private" }, { "name": "Robert", "profile_status": "private" } ] </code></pre> <p>So the question is Why django permissions are used this way? Why drf permissions are not applied for every instance?</p> <p>Thank you!</p>
0
2016-10-03T19:38:12Z
39,839,545
<p>It is expensive computationally to do this for every user. Imagine if you had hundreds of thousands of them. In the <a href="http://www.django-rest-framework.org/api-guide/permissions/#limitations-of-object-level-permissions" rel="nofollow">docs</a>:</p> <blockquote> <p><strong>Limitations of object level permissions</strong></p> <p>For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.</p> <p>Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.</p> </blockquote> <p>A work around is probably just to override the list view and use <code>.filter(profile_status__exact='public'</code></p>
1
2016-10-03T20:04:58Z
[ "python", "django", "permissions", "django-rest-framework" ]
TypeError: unsupported operand type(s) for *: 'PCA' and 'float'
39,839,310
<p>EDIT:</p> <p>Here is the head of the data csv:</p> <pre><code> Fresh Milk Grocery Frozen Detergents_Paper Delicatessen 0 12669 9656 7561 214 2674 1338 1 7057 9810 9568 1762 3293 1776 2 6353 8808 7684 2405 3516 7844 3 13265 1196 4221 6404 507 1788 4 22615 5410 7198 3915 1777 5185 </code></pre> <p>Error I'm seeing:</p> <pre><code>TypeError: unsupported operand type(s) for *: 'PCA' and 'float' </code></pre> <p>Code:</p> <pre><code>from sklearn.decomposition import PCA log_data = np.log(data) # TODO: Apply PCA to the good data with the same number of dimensions as features pca = PCA(n_components=4) # TODO: Apply a PCA transformation to the sample log-data pca_samples = pca.fit(log_data) # Generate PCA results plot pca_results = rs.pca_results(good_data, pca) display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values)) </code></pre> <p>It's complaining about the last line</p> <p>data is from a csv that has been shown to work fine. </p>
0
2016-10-03T19:48:31Z
39,839,691
<p><code>PCA.fit()</code> tansforms the model in-place and returns <code>self</code> so that you can chain other model operations. So, after</p> <pre><code>pca_samples = pca.fit(log_data) </code></pre> <p><code>pca_samples</code> is just another reference to <code>pca</code>.</p>
0
2016-10-03T20:15:51Z
[ "python", "scikit-learn", "sklearn-pandas" ]
When plotting with Bokeh, how do you automatically cycle through a color pallette?
39,839,409
<p>I want to use a loop to load and/or modify data and plot the result within the loop using Bokeh (I am familiar with <a href="http://matplotlib.org/1.2.1/examples/api/color_cycle.html" rel="nofollow">Matplotlib's <code>axes.color_cycle</code></a>). Here is a simple example</p> <pre><code>import numpy as np from bokeh.plotting import figure, output_file, show output_file('bokeh_cycle_colors.html') p = figure(width=400, height=400) x = np.linspace(0, 10) for m in xrange(10): y = m * x p.line(x, y, legend='m = {}'.format(m)) p.legend.location='top_left' show(p) </code></pre> <p>which generates this plot</p> <p><img src="http://i.stack.imgur.com/9OtK9.png" alt="bokeh plot"></p> <p>How do I make it so the colors cycle without coding up a list of colors and a modulus operation to repeat when the number of colors runs out? </p> <p>There was some discussion on GitHub related to this, issues <a href="https://github.com/bokeh/bokeh/issues/351" rel="nofollow">351</a> and <a href="https://github.com/bokeh/bokeh/issues/2201" rel="nofollow">2201</a>, but it is not clear how to make this work. The four hits I got when searching the <a href="http://bokeh.pydata.org/en/latest/search.html?q=cycle+colors" rel="nofollow">documentation</a> for <code>cycle color</code> did not actually contain the word <code>cycle</code> anywhere on the page.</p>
2
2016-10-03T19:56:25Z
39,840,381
<p>It is probably easiest to just get the list of colors and cycle it yourself using <a href="https://docs.python.org/3.5/library/itertools.html" rel="nofollow"><code>itertools</code></a>: </p> <pre><code>import numpy as np from bokeh.plotting import figure, output_file, show # select a palette from bokeh.palettes import Dark2_5 as palette # itertools handles the cycling import itertools output_file('bokeh_cycle_colors.html') p = figure(width=400, height=400) x = np.linspace(0, 10) # create a color iterator colors = itertools.cycle(palette) for m, color in itertools.izip(xrange(10), colors): y = m * x p.line(x, y, legend='m = {}'.format(m), color=color) p.legend.location='top_left' show(p) </code></pre> <p><a href="http://i.stack.imgur.com/L7l9G.png" rel="nofollow"><img src="http://i.stack.imgur.com/L7l9G.png" alt="enter image description here"></a></p> <p>There does seem to be a <code>cycle_colors</code> function in <code>bokeh/charts/utils.py</code>, but it doesn't seem to be called anywhere else in the library, and it seems to be doing the exact same thing.</p> <p>Here is an example demonstrating one of the many palettes available in <a href="https://stanford.edu/~mwaskom/software/seaborn/" rel="nofollow">seaborn</a> (they have anything you would expect from <code>matplotlib</code> and more):</p> <pre><code>import numpy as np from bokeh.plotting import figure, output_file, show # seaborn handles the color palette generation, itertools handles the cycling import seaborn.apionly as sns import itertools output_file('bokeh_cycle_colors.html') p = figure(width=400, height=400) x = np.linspace(0, 10) # define the color palette ncolors = 5 palette = sns.palettes.color_palette('colorblind', ncolors) # as hex is necessary for bokeh to render the colors properly. colors = itertools.cycle(palette.as_hex()) for m, color in itertools.izip(xrange(10), colors): y = m * x p.line(x, y, legend='m = {}'.format(m), color=color) p.legend.location='top_left' show(p) </code></pre> <p><a href="http://i.stack.imgur.com/ugH9o.png" rel="nofollow"><img src="http://i.stack.imgur.com/ugH9o.png" alt="enter image description here"></a></p>
3
2016-10-03T21:02:42Z
[ "python", "plot", "bokeh" ]
Python user input file path
39,839,450
<p>I am working on an easy project which requires user input a path for program and goes to this path Here, I Worte on OSX: </p> <pre><code>from pathlib import Path def main(): user_input_path = Path(input()) </code></pre> <p>And debug like this</p> <pre><code>&gt;&gt;&gt; /Users/akrios/Desktop/123 SyntaxError: invalid syntax </code></pre>
0
2016-10-03T19:58:41Z
39,840,693
<p>The <code>input()</code> function reads in the input, and then tries to parse it as if it's something in Python notation. Instead, use the <code>raw_input()</code> function, it does not parse anything and returns the input as a string.</p>
0
2016-10-03T21:28:13Z
[ "python" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case of a tie, return the smaller value. Returns the exponent. ''' result=0 exp=1 while base**exp&lt;num: if base**exp &lt;= num &lt; base**(exp+1): result = exp elif num - base**exp &lt;= base**(exp+1) - num: result=exp+1 exp+=1 return result </code></pre> <p>In my code, when I try running <code>closest_power(4,62)</code> it returns <code>2</code> instead of <code>3</code> and, in similar test cases like <code>closest_power(4, 12)</code> returns <code>1</code> instead of <code>2</code>. (<code>closest_power(5, 22)</code> returns <code>1</code> instead of <code>2</code>) </p> <p>For rest of the test cases it works fine for example: </p> <pre><code>closest_power(2, 384.0) </code></pre> <p>returns <code>8</code>.</p> <p>Why am I missing out those cases?</p>
2
2016-10-03T20:04:12Z
39,840,248
<p>Your first condition is always true until while condition violated. For example if <code>exp=1</code> => <code>4**1 &lt;= 64 &lt; 4**(1+1)</code> yields to true. If <code>exp=2</code> => <code>4**2 &lt;= 64 &lt; 4**(2+1)</code> also yields to true.</p> <p>And when condition violated result is always equals to smaller exponent (result=exp). So calling <code>closest_power(4,62)</code> is same as calling <code>closest_power(4,18)</code> and returns <code>2</code>. </p> <p>As @wim said your method is too complicated. Something like below would be more clear:</p> <pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case of a tie, return the smaller value. Returns the exponent. ''' exp=1 while base ** exp &lt; num: exp+=1 return exp if base ** exp - num &lt; num - base ** (exp - 1) else exp - 1 </code></pre>
4
2016-10-03T20:54:04Z
[ "python", "python-3.x" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case of a tie, return the smaller value. Returns the exponent. ''' result=0 exp=1 while base**exp&lt;num: if base**exp &lt;= num &lt; base**(exp+1): result = exp elif num - base**exp &lt;= base**(exp+1) - num: result=exp+1 exp+=1 return result </code></pre> <p>In my code, when I try running <code>closest_power(4,62)</code> it returns <code>2</code> instead of <code>3</code> and, in similar test cases like <code>closest_power(4, 12)</code> returns <code>1</code> instead of <code>2</code>. (<code>closest_power(5, 22)</code> returns <code>1</code> instead of <code>2</code>) </p> <p>For rest of the test cases it works fine for example: </p> <pre><code>closest_power(2, 384.0) </code></pre> <p>returns <code>8</code>.</p> <p>Why am I missing out those cases?</p>
2
2016-10-03T20:04:12Z
39,840,284
<p>I suppose <code>elif</code> is extra. If condition is satisfied, you should return the value.</p> <pre><code>def closest_power2(base, num): exp=1 while base**exp&lt;=num: if base**exp &lt;= num &lt;= base**(exp+1): num_low = base**exp num_high = base**(exp+1) return exp if num-num_low&lt;num_high-num else exp+1 exp += 1 return 0 </code></pre> <p>Emm... In your case, for <code>exp=8</code>, the first <code>if</code> condition is satisfied. Then you assign <code>result=exp</code> (which is 8) and at the next iteration <code>while</code> breaks, because <code>2^9</code> is not less than <code>384</code>, so you return <code>8</code>.</p> <p>Please notice, I've changed <code>base**exp&lt;num</code> to <code>base**exp&lt;=num</code>.</p>
0
2016-10-03T20:56:16Z
[ "python", "python-3.x" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case of a tie, return the smaller value. Returns the exponent. ''' result=0 exp=1 while base**exp&lt;num: if base**exp &lt;= num &lt; base**(exp+1): result = exp elif num - base**exp &lt;= base**(exp+1) - num: result=exp+1 exp+=1 return result </code></pre> <p>In my code, when I try running <code>closest_power(4,62)</code> it returns <code>2</code> instead of <code>3</code> and, in similar test cases like <code>closest_power(4, 12)</code> returns <code>1</code> instead of <code>2</code>. (<code>closest_power(5, 22)</code> returns <code>1</code> instead of <code>2</code>) </p> <p>For rest of the test cases it works fine for example: </p> <pre><code>closest_power(2, 384.0) </code></pre> <p>returns <code>8</code>.</p> <p>Why am I missing out those cases?</p>
2
2016-10-03T20:04:12Z
39,861,647
<p>this works.</p> <pre><code>def closest_power(base, num): bevaluate = True exponent = 0 vale = 0 older = 0 olders = 0 while bevaluate: vale = base ** exponent if vale &lt; num: older = num - vale exponent+=1 else: olders = vale - num if older == olders : if num == 1: exponent = 0 else: exponent-=1 break elif older &lt; olders: exponent-=1 break bevaluate = False return exponent </code></pre>
0
2016-10-04T20:59:53Z
[ "python", "python-3.x" ]
depth first search in an undirected, weighted graph using adjacency matrix?
39,839,695
<p>I don't want the answer, but I'm having trouble keeping track of the nodes. Meaning, say I have nodes 0, 1, 2, 3,4, 5, 6, 7, where 0 is start, and 7 is goal, I made an adjacency matrix like so: </p> <pre><code>[ [0, 3, 0, 0, 4, 0, 0, 0], [3, 0, 0, 0, 5, 0, 8, 0], [0, 0, 0, 4, 0, 5, 0, 0], [0, 0, 4, 0, 0, 0, 0, 14], [4, 5, 0, 0, 0, 2, 0, 0], [0, 0, 5, 0, 2, 0, 4, 0], [0, 8, 0, 5, 0, 4, 0, 0], [0, 0, 0, 14, 0, 0, 0, 0] ] </code></pre> <p>if it's a 0, there is no link between the nodes, otherwise, if it's greater than 1, then the number is the weight of the edge between those nodes.</p> <p>I'm having trouble identifying what the actual node would be, versus a path.</p> <p>I can find the goal, but I wouldn't know how to show the path to the goal, and what the total weight would be?</p> <p>EDIT: Here is what I am trying to achieve (this will not work, but this is the general idea):</p> <pre><code>def dfs(graph, start, goal): stack = [] visited = [] stack.append(graph[start]) visited.append(start) while (len(stack) != 0): current_node = stack.pop() if current_node not in visited: visited.append(current_node) if current_node = goal: return path else: for nodes in current_node: if nodes not in visited: stack.append(nodes) </code></pre> <p>if the edges were unweighed this would be easier, but I'm basically adding all neighbors of the current node as long as I haven't visited it to the stack, until I find the goal node, and then I want to return the path. but in this case I know it's broken because 1) I'm not sure how to check if it's the goal node, since I'm only storing the nodes neighbors, and 2) not checking for the full path.</p>
0
2016-10-03T20:15:57Z
39,840,165
<p>Maintain a <code>path variable</code> to store the vertex as u encounter them. When u found <code>end</code> vertex, the path variable will have the path. </p> <p>Find the pseudo code for reference. Pardon any minor mistake in the code</p> <pre><code>DFS (vertex start, vertex end, Graph G, list path): if(start==end): return TRUE for vertex in adjacent(start): if vertex not in path: # has not been traversed path = path + [vertex] a = DFS(vertex, end, G, path) if a==TRUE: # end vertex was found return TRUE path.delete(vertex) # delete the vertex added,as its not in the path from start to end </code></pre> <p>Acc. to your code, when u found the goal vertex, the visited stack is contains the element in the path. </p> <p>I hope it helped. </p>
1
2016-10-03T20:47:53Z
[ "python", "algorithm", "search", "graph", "tree" ]
IPython: Does "%matplotlib inline" required before importing matplotlib?
39,839,721
<p>I am using IPython. Got confused that the codes can't execute if I don't add</p> <pre><code>%matplotlib </code></pre> <p>before </p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p>Could someone enlighten me by explaining why the magic function call in IPython is needed for matplotlib usage?</p>
0
2016-10-03T20:17:29Z
39,839,811
<p>I believe it's needed because normally matplotlib opens additional windows for graphs using a default toolkit. The %inline lets you load graphs in the IPython notebook, instead of using an external toolkit.</p>
3
2016-10-03T20:23:40Z
[ "python", "matplotlib", "ipython" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox', 'jumped', 'over'], 'testing-1.30.14': ['lazy', 'dog'], 'testing-1.30.8': ['the'], 'testing-1.30.0': ['The', 'quick'], 'testing-1.30.10': ['The', 'quick'], 'testing-1.30.11': ['brown'], 'testing-1.30.7': ['fox', 'jumped', 'over'], 'testing-1.30.9': ['lazy', 'dog'] } </code></pre> <p>Do some sorting</p> <pre><code>bar = sortfoo(foo) </code></pre> <p>Desired output:</p> <pre><code>for item in bar: print '{}: {}'.format(item, bar[item]) testing-1.30.0: ['The', 'quick'] testing-1.30.1: ['brown'] testing-1.30.2: ['fox', 'jumped', 'over'] testing-1.30.3: ['the'] testing-1.30.4: ['lazy', 'dog'] testing-1.30.5: ['The', 'quick'] testing-1.30.6: ['brown'] testing-1.30.7: ['fox', 'jumped', 'over'] testing-1.30.8: ['the'] testing-1.30.9: ['lazy', 'dog'] testing-1.30.10: ['The', 'quick'] testing-1.30.11: ['brown'] testing-1.30.12: ['fox', 'jumped', 'over'] testing-1.30.13: ['the'] testing-1.30.14: ['lazy', 'dog'] </code></pre> <p>Ideally I would like this to be pythonic, in that I wouldn't do something crazy like splitting the key into components and building a new dictionary based off that;</p> <p>What I tried:</p> <pre><code>from collections import OrderedDict od = OrderedDict(sorted(foo.items())) print '{}: {}'.format(item, od[item]) </code></pre> <p>Thank you</p>
0
2016-10-03T20:17:48Z
39,839,831
<p>Got it! nevermind, found LooseVersion / strict versions</p> <pre><code>from distutils.version import LooseVersion from collections import OrderedDict orderedKeys = sorted(foo, key=LooseVersion) odict = OrderedDict((key, foo[key]) for key in orderedKeys) for item in odict: print '{}: {}'.format(item, odict[item]) </code></pre>
0
2016-10-03T20:24:58Z
[ "python", "sorting", "dictionary", "key", "versions" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox', 'jumped', 'over'], 'testing-1.30.14': ['lazy', 'dog'], 'testing-1.30.8': ['the'], 'testing-1.30.0': ['The', 'quick'], 'testing-1.30.10': ['The', 'quick'], 'testing-1.30.11': ['brown'], 'testing-1.30.7': ['fox', 'jumped', 'over'], 'testing-1.30.9': ['lazy', 'dog'] } </code></pre> <p>Do some sorting</p> <pre><code>bar = sortfoo(foo) </code></pre> <p>Desired output:</p> <pre><code>for item in bar: print '{}: {}'.format(item, bar[item]) testing-1.30.0: ['The', 'quick'] testing-1.30.1: ['brown'] testing-1.30.2: ['fox', 'jumped', 'over'] testing-1.30.3: ['the'] testing-1.30.4: ['lazy', 'dog'] testing-1.30.5: ['The', 'quick'] testing-1.30.6: ['brown'] testing-1.30.7: ['fox', 'jumped', 'over'] testing-1.30.8: ['the'] testing-1.30.9: ['lazy', 'dog'] testing-1.30.10: ['The', 'quick'] testing-1.30.11: ['brown'] testing-1.30.12: ['fox', 'jumped', 'over'] testing-1.30.13: ['the'] testing-1.30.14: ['lazy', 'dog'] </code></pre> <p>Ideally I would like this to be pythonic, in that I wouldn't do something crazy like splitting the key into components and building a new dictionary based off that;</p> <p>What I tried:</p> <pre><code>from collections import OrderedDict od = OrderedDict(sorted(foo.items())) print '{}: {}'.format(item, od[item]) </code></pre> <p>Thank you</p>
0
2016-10-03T20:17:48Z
39,839,834
<p>Sort <code>foo</code> with an appropriate sort key. You'd have to chop off the "testing-" part, then split the rest on the periods, then turn each of those into an integer. Also, the result will be a list of keys, so look up those items in the original dictionary.</p> <pre><code>&gt;&gt;&gt; bar = sorted(foo, key=lambda x: map(int, x.split('-')[1].split('.'))) &gt;&gt;&gt; for item in bar: ... print '{}: {}'.format(item, foo[item]) ... testing-1.30.0: ['The', 'quick'] testing-1.30.1: ['brown'] testing-1.30.2: ['fox', 'jumped', 'over'] testing-1.30.3: ['the'] testing-1.30.4: ['lazy', 'dog'] testing-1.30.5: ['The', 'quick'] testing-1.30.6: ['brown'] testing-1.30.7: ['fox', 'jumped', 'over'] testing-1.30.8: ['the'] testing-1.30.9: ['lazy', 'dog'] testing-1.30.10: ['The', 'quick'] testing-1.30.11: ['brown'] testing-1.30.12: ['fox', 'jumped', 'over'] testing-1.30.13: ['the'] testing-1.30.14: ['lazy', 'dog'] </code></pre> <p>Note that for Python 3 you would have to wrap the <code>map()</code> in <code>list()</code> or <code>tuple()</code> to consume the lazy <code>map</code> object.</p>
1
2016-10-03T20:25:23Z
[ "python", "sorting", "dictionary", "key", "versions" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox', 'jumped', 'over'], 'testing-1.30.14': ['lazy', 'dog'], 'testing-1.30.8': ['the'], 'testing-1.30.0': ['The', 'quick'], 'testing-1.30.10': ['The', 'quick'], 'testing-1.30.11': ['brown'], 'testing-1.30.7': ['fox', 'jumped', 'over'], 'testing-1.30.9': ['lazy', 'dog'] } </code></pre> <p>Do some sorting</p> <pre><code>bar = sortfoo(foo) </code></pre> <p>Desired output:</p> <pre><code>for item in bar: print '{}: {}'.format(item, bar[item]) testing-1.30.0: ['The', 'quick'] testing-1.30.1: ['brown'] testing-1.30.2: ['fox', 'jumped', 'over'] testing-1.30.3: ['the'] testing-1.30.4: ['lazy', 'dog'] testing-1.30.5: ['The', 'quick'] testing-1.30.6: ['brown'] testing-1.30.7: ['fox', 'jumped', 'over'] testing-1.30.8: ['the'] testing-1.30.9: ['lazy', 'dog'] testing-1.30.10: ['The', 'quick'] testing-1.30.11: ['brown'] testing-1.30.12: ['fox', 'jumped', 'over'] testing-1.30.13: ['the'] testing-1.30.14: ['lazy', 'dog'] </code></pre> <p>Ideally I would like this to be pythonic, in that I wouldn't do something crazy like splitting the key into components and building a new dictionary based off that;</p> <p>What I tried:</p> <pre><code>from collections import OrderedDict od = OrderedDict(sorted(foo.items())) print '{}: {}'.format(item, od[item]) </code></pre> <p>Thank you</p>
0
2016-10-03T20:17:48Z
39,839,839
<p>In the sort function, split the key on <code>'.'</code> and cast the last item in the <em>splitted</em> list to integer:</p> <pre><code>for k in sorted(foo, key=lambda x: int(x.rsplit('.')[-1])): print('{}: {}'.format(k, foo[k])) </code></pre> <hr> <p>Output:</p> <pre><code>testing-1.30.0: ['The', 'quick'] testing-1.30.1: ['brown'] testing-1.30.2: ['fox', 'jumped', 'over'] testing-1.30.3: ['the'] testing-1.30.4: ['lazy', 'dog'] testing-1.30.5: ['The', 'quick'] testing-1.30.6: ['brown'] testing-1.30.7: ['fox', 'jumped', 'over'] testing-1.30.8: ['the'] testing-1.30.9: ['lazy', 'dog'] testing-1.30.10: ['The', 'quick'] testing-1.30.11: ['brown'] testing-1.30.12: ['fox', 'jumped', 'over'] testing-1.30.13: ['the'] testing-1.30.14: ['lazy', 'dog'] </code></pre>
0
2016-10-03T20:25:35Z
[ "python", "sorting", "dictionary", "key", "versions" ]
Pandas: Summing arrays as as an aggregation with multiple groupby columns
39,839,748
<p>I'm using Python 3.5.1 and Pandas 0.18.0.</p> <p>Let's say I have a Pandas dataframe with multiple columns. The dataframe has one column that includes a numpy array. Here is an example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; df = pd.DataFrame([{'A': 'Label1', 'B': 'yellow', 'C': np.array([0,0,0]), 'D': 1}, {'A': 'Label2', 'B': 'yellow', 'C': np.array([1,1,1]), 'D': 4}, {'A': 'Label1', 'B': 'yellow', 'C': np.array([1,0,1]), 'D': 2}, {'A': 'Label2', 'B': 'green', 'C': np.array([1,1,0]), 'D': 3}]) &gt;&gt;&gt; df A B C D 0 Label1 yellow [0, 1, 0] 1 1 Label2 yellow [1, 1, 1] 4 2 Label1 yellow [1, 0, 1] 2 3 Label2 green [1, 1, 0] 3 </code></pre> <p>I want to create a dataframe that groups by columns A and B and aggregates columns C and D with a sum. <strong>Like this:</strong></p> <pre class="lang-py prettyprint-override"><code> C D A B Label1 yellow [1, 1, 1] 3 Label2 green [1, 1, 0] 3 yellow [1, 1, 1] 4 </code></pre> <p>When I try and do the aggregation using the entire dataframe, column C (the one with the numpy arrays) is not returned:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df.groupby(['A','B']).sum() D A B Label1 yellow 3 Label2 green 3 yellow 4 </code></pre> <p>If I ignore column D and only attempt to output column C, I get an error:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[['A','B','C']].groupby(['A','B']).sum() Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\pandas\core\groupby.py", line 96, in f return self._cython_agg_general(alias, numeric_only=numeric_only) File "C:\Anaconda3\lib\site-packages\pandas\core\groupby.py", line 3038, in _cython_agg_general how, numeric_only=numeric_only) File "C:\Anaconda3\lib\site-packages\pandas\core\groupby.py", line 3084, in _cython_agg_blocks raise DataError('No numeric types to aggregate') pandas.core.base.DataError: No numeric types to aggregate </code></pre> <p>If I group by only a single column and only output my array column, the arrays sum correctly:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[['A','C']].groupby(['A']).sum() C A Label1 [1, 1, 1] Label2 [2, 2, 1] </code></pre> <p>But if I try to include the scalar column as an aggregate as well, my array column again is not returned:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[['A','C','D']].groupby(['A']).sum() D A Label1 3 Label2 7 </code></pre> <p>Also, if I try and include column B (contains strings) in the aggregate function, columns B and C return but column D does not:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df[['A','B','C']].groupby(['A']).sum() B C A Label1 yellowyellow [1, 1, 1] Label2 yellowgreen [2, 2, 1] </code></pre> <p>Can anyone explain why this is happening? I know I could create a [A+B] column and then group by that, sum my array column, and then merge the result it back in with the rest of my data on column [A+B], but it seems like there should be a much simpler way. Any ideas?</p>
1
2016-10-03T20:19:15Z
39,839,979
<p><code>pd.concat</code> separate groupbys is a workaround</p> <pre><code>g = df.groupby(['A', 'B']) pd.concat([g.C.apply(np.sum), g.D.sum()], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/HzryQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/HzryQ.png" alt="enter image description here"></a></p>
0
2016-10-03T20:36:32Z
[ "python", "pandas", "numpy" ]
How to display a terminal-like environment, that shows the output of Python scripts, within a web browser?
39,839,795
<p>I've recently finished my courses in HTML and CSS, and am now sailing into Javascript. I have a decent background in Python at the moment, and would like to utilize my experience for web programming. </p> <p>My question being, how could I go about creating a terminal environment that could display my python code within my HTML page? For example, if I had a script named <code>hello.py</code>, and it printed a <code>hello world</code> message to the user, how could I take that script, and display its outcome within my page, so when you loaded it up, it would read 'hello world'?</p> <p>I hope this is clear. I'm not referencing using Python to display HTML, like a framework like Django, but rather how to take a script, run it, and display its output to a web page? </p>
0
2016-10-03T20:22:49Z
39,839,976
<p>Leaving aside the security problems, you can do this in several ways.</p> <p>You can pursue a "stateless, sort of" approach, which is simpler, by displaying a fake user prompt in CSS and supplying a textarea or input area that manages to emulate a command line. When the user hits ENTER you would get the input, send it for execution to the local shell and capture the output, then display it back formatting it as a terminal would. This could be done better in AJAX, I think.</p> <p>Since you work in Python this is <a href="http://stackoverflow.com/questions/28957258/twisted-run-local-shell-commands-with-pipeline">a related question and answer</a> for twisted.</p> <p>The above method only allows you very simple (but still dangerous :-) ) interactions. If you launched a <code>ncurses</code> program or any kind of interactive program which attempts to read input, you'd get immediately stuck. This is enough to run your <code>hello.py</code>, however.</p> <p>You can improve on the method using tested libraries such as <a href="http://terminal.jcubic.pl/" rel="nofollow">this jQuery plugin</a>.</p> <p>A more complex way would be to allocate a terminal locally (one per each user session), capture all keyboard events and "echo" them to the terminal, and read the console. You would need to know how to offer a valid terminal environment with appropriate capabilities, and then you'd need to decode the program output (complete with ANSI terminal commands) and "rebuild" the (virtual) monitor appearance, then send this "monitor" view to the client browser to be displayed somehow (AJAX, websockets...). The results would be way better, but the effort would be proportionally greater.</p> <p>This latter approach (in Python) leads to projects such as <a href="https://github.com/liftoff/GateOne" rel="nofollow">this</a>, or <a href="https://github.com/paradoxxxzero/butterfly" rel="nofollow">this</a>, which communicates with the client through websockets.</p> <h1>UPDATE</h1> <p>All this is <strong>not needed</strong> to do what you require; you seem to need something between a module executor (not sure of this) plus a chat function (this looks mandatory).</p> <p>What you need is to <em>abstract</em> the input and output of your program so that it can "talk" to the web browser. In this case you might run your program as a daemon (there are modules that allow daemonizing a stdio-based program). Then, the user interface (you can use the jQuery plugin) collects player A's input and sends it to the program, collects the output and sends it back to A's screen. You need to think about temporizations and asynchronicity, or turn management: player A might type in five commands while player B slowly types only one. Also, going on, you'll have to manage sessions and disconnects/reconnects of users.</p> <p>Unfortunately, the "Web" world is quite different in its approaches and problems from the "keyboard" world.</p>
0
2016-10-03T20:36:21Z
[ "python", "html", "web" ]
Compose a function that sorts a list known to have exactly three values efficiently (Sage(python))
39,839,823
<p>First of all I am not allow to use any of the internal command that sort the list not any of the other sorted method such as Selection, buble. Compose a function that sorts a list known to have exactly two values this is what I have done : </p> <pre><code>def sort_Two_values(list): Sorted_List=[] Sorted_List.append(list[0]) for i in range(1,len(list)): if (list[i-1]&gt;list[i]): Sorted_List.insert(0,list[i]) elif (list[i-1]&lt;list[i]): Sorted_List.append(list[i]) else: if (list[i]==Sorted_List[0]): Sorted_List.insert(0,list[i]) else: Sorted_List.append(list[i]) return Sorted_List </code></pre> <p>sort_Two_values([1,0,0,0,0,0,1,1,0])</p> <p>It seems to be working well! </p> <p>Now, I am trying to do that for three values. For example [1,0,0,0,2,2,1,0,0,2] Would someone help me out with that ! </p>
0
2016-10-03T20:24:16Z
39,840,015
<p>All you needs is to push <code>0 to beginning, 2 to last</code> of list and <code>1 will remain wherever it is</code>. By the end of the loop, you will have a sorted list. </p>
0
2016-10-03T20:39:09Z
[ "python", "sage" ]
Interger being decremented too much in for loop in Python
39,839,832
<p>This is a school project and I'm having slight trouble with one piece of the code. This is a background: I'm making a hangman game, and it works fine, but I'm trying to make the loop decrement an integer only if the if statement above it is false. This, seems to be a problem as it decrements the integer way too much, for example instead of 10 to 9, it decrements it from 10 to 4. Any help is appreciated. Here is the code:</p> <pre><code> # This will run when count is above 0 (the length of the word.) while guessesLeft &gt; 0: # Calls letterGuessQuery from the guessing module - gives the user the ability to guess a letter. guessing.letterGuessQuery(guessesLeft,guessedLetters,coveredWord) # Calls letterGuess from the guessing module. guessing.letterGuess(guessedLetters) # Gives the lenght of the randomWord - I use it as an index - I store in it i. for i in range(len(randomWord)): # Loops through randomWord and stores it in x for x in randomWord[i]: # Loops through the guessedLetters. for z in guessedLetters: # If the guessed letter is equal to the letter in random word. if x == z: # Modifies covered word to show the correct letter. coveredWord[i] = x else: guessesLeft -=1 </code></pre>
0
2016-10-03T20:24:58Z
39,840,144
<p>Without seeing more of your code I would think that you are going to need a separate block that defines when the player input is incorrect instead of trying to use the same block that defines when the player input is correct.</p> <p>Your current block is iterating once for every letter in <code>randomWord</code> which works for the latter but not the former.</p> <p>Separate your nesting blocks.</p>
0
2016-10-03T20:46:57Z
[ "python", "for-loop", "while-loop" ]
AttributeError: '<class 'praw.objects.MoreComments'>' has no attribute 'score'
39,839,968
<p>Not sure how to fix this? Please guide:</p> <pre><code>import praw r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit('iama') top_year_subreddit = subreddit.get_top_from_year submissions = top_year_subreddit(limit=50) for submission in submissions: #submission.replace_more_comments(limit=None, threshold=0) all_comments = praw.helpers.flatten_tree(submission.comments) all_comments.sort(key = lambda comment : comment.score, reverse = True) top_comments = all_comments[:30] for comment in top_comments: print(comment.body) ~ </code></pre> <p>The error is:</p> <pre><code>$ python getSubmissionsFromSubreddit.py Traceback (most recent call last): File "getSubmissionsFromSubreddit.py", line 10, in &lt;module&gt; all_comments.sort(key = lambda comment : comment.score, reverse = True) File "getSubmissionsFromSubreddit.py", line 10, in &lt;lambda&gt; all_comments.sort(key = lambda comment : comment.score, reverse = True) File "/usr/local/lib/python2.7/dist-packages/praw/objects.py", line 92, in __getattr__ raise AttributeError(msg) AttributeError: '&lt;class 'praw.objects.MoreComments'&gt;' has no attribute 'score' </code></pre> <p>Here's the gist: <a href="https://gist.github.com/monajalal/e3eb0590bc0a4f757500ec423f2b6dd3" rel="nofollow">https://gist.github.com/monajalal/e3eb0590bc0a4f757500ec423f2b6dd3</a></p> <p>I updated my code to this and still get error for retrieving top comments:</p> <pre><code>import praw subreddit_name = 'nostalgia' num_submissions = 2 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top_submissions = subreddit.get_top_from_year(limit = num_submissions, comment_sort='top') for submission in top_submissions: submission.replace_more_comments(limit=None, threshold=0) all_comments = praw.helpers.flatten_tree(submission.comments) if len(all_comments) &gt; 100: print(len(all_comments)) top_comments = all_comments.sort(key = lambda comment : comment.score, reverse = True) for comment in top_comments[:10]: print(comment.body) else: continue </code></pre> <p>I get this error:</p> <pre><code>148 Traceback (most recent call last): File "getSubmissionsFromSubreddit.py", line 14, in &lt;module&gt; for comment in top_comments[:10]: TypeError: 'NoneType' object has no attribute '__getitem__' </code></pre>
0
2016-10-03T20:36:05Z
39,841,375
<p>Here's the correct answer:</p> <pre><code>import praw subreddit_name = 'nostalgia' num_submissions = 2 num_top_comments = 10 num_comments_per_submission = 500 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top_submissions = subreddit.get_top_from_year(limit = num_submissions, comment_limit=num_comments_per_submission, comment_sort='top') for submission in top_submissions: submission.replace_more_comments(limit=None, threshold=0) all_comments = praw.helpers.flatten_tree(submission.comments) if len(all_comments) &gt; 100: print(len(all_comments)) top_comments = sorted(all_comments, key=lambda comment: -comment.score) for comment in top_comments[:10]: print(comment.body) if comment.author != None: print('{0}: {1}'.format('Author name', comment.author.name)) else: print('Author account is DELETED') print('{0}: {1}'.format('Comment score is', comment.score)) else: continue </code></pre>
0
2016-10-03T22:27:07Z
[ "python", "reddit", "praw", "reddit-api" ]
SSH into VM and run "git pull" using Paramiko - Python
39,839,975
<p>I'm trying to SSH into my VM and did perform a <code>git pull</code> </p> <ul> <li>the SSH seems to be working fine </li> <li>the git pull seem to be executed</li> <li>but when I provide password, it doesn't seem to take it </li> <li>Am I missing something ? </li> </ul> <hr> <p>I have </p> <pre><code>import paramiko import time import sys import os import pdb # Note # sudo pip install --user paramiko ip = "111.111.111.111" un = "root" pw = "abc" def ssh_con (ip, un, pw): global ssh ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=un, password=pw) def cmd_io (command): global ssh_cmd ssh_cmd.send("%s \n" %command) time.sleep(1) output = ssh_cmd.recv(10000).decode("utf-8") print (output) ssh_con(ip,un,pw) ssh_cmd = ssh.invoke_shell() print ("SSH CONNECTION ESTABLISHED TO %s" % ip) cmd_io("git pull") time.sleep(2) cmd_io(pw) </code></pre> <hr> <p>I kept getting </p> <pre><code>git pull Enter passphrase for key '/root/.ssh/id_rsa': Enter passphrase for key '/root/.ssh/id_rsa': </code></pre>
0
2016-10-03T20:36:20Z
39,840,140
<p>It looks like your SSH Rsa Key pair has been setup up with a pass phrase for root on 111.111.111.111. You can recreate the ssh rsa key with:</p> <pre><code>ssh-keygen -t rsa </code></pre> <p>and just leave pass phrase blank.</p>
0
2016-10-03T20:46:49Z
[ "python", "git", "ssh", "paramiko" ]
Finding first event in one table that occurred after event in a second table, per row
39,840,012
<p>I have a pandas DataFrame that looks like this:</p> <pre><code>email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16 </code></pre> <p>I have a second pandas DataFrame with related events, when a signup actually got followed through on, that looks like this:</p> <pre><code>email call_date a@a.com 7/25/16 b@b.com 6/20/16 b@b.com 5/4/16 </code></pre> <p>There are a few things to keep in mind. </p> <ul> <li>Some of the <code>signup_date</code>s may not have any later <code>call_date</code> for the corresponding email. That is, some people sign up but never get a call back.</li> <li>Some people signup more than once and get called after each signup.</li> <li>Some people signup more than once but don't get called after each signup.</li> <li>Some people signup more than once but may only get called after several signups. In this case we want to attribute the call to the most recent signup.</li> </ul> <p>Ultimately the goal is to determine whether there is a call event that came after a sign up event for a given user but before the next sign up event for the same user, where the number of signup events per user is not known in advance. </p> <p>Is there a <code>pandas</code> best practices way to do this? For now I'm using a for loop, and it's extremely slow (hasn't finished on 100,000 rows even after 20 minutes):</p> <pre><code>response_date = [] for i in range(signups.shape[0]): unique_id = signups.unique_id.values[i] start_date = signups.signup_date.values[i] end_date = signups.signup_date.values[-1] if end_date is start_date: end_date = end_date + pd.Timedelta('1 year') tmp_df = calls[calls.unique_id == unique_id] tmp_df = tmp_df[tmp_df.timestamp &gt; start_date][tmp_df.timestamp &lt; end_date] tmp_df = tmp_df.sort_values('timestamp') if tmp_df.shape[0] &gt; 0 : response_date.append(tmp_df.timestamp.values[0]) else: response_date.append(None) </code></pre> <p>Thanks for any advice!</p>
0
2016-10-03T20:38:50Z
39,845,781
<p><strong><em>setup</em></strong></p> <pre><code>from StringIO import StringIO import pandas as pd txt1 = """email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16""" df1 = pd.read_csv(StringIO(txt1), parse_dates=[1], delim_whitespace=True) txt2 = """email call_date a@a.com 7/25/16 b@b.com 6/20/16 b@b.com 5/4/16""" df2 = pd.read_csv(StringIO(txt2), parse_dates=[1], delim_whitespace=True) </code></pre> <p><strong><em>merge</em></strong><br> combine <code>df1</code> and <code>df2</code> on <code>email</code></p> <pre><code>df = df1.merge(df2) df </code></pre> <p><a href="http://i.stack.imgur.com/SHMab.png" rel="nofollow"><img src="http://i.stack.imgur.com/SHMab.png" alt="enter image description here"></a></p> <p><strong><em>filter 1</em></strong><br> get rid of rows where <code>call_date</code> is prior to <code>signup_date</code></p> <pre><code>cond1 = df.signup_date.le(df.call_date) cond1 0 True 1 True 2 False 3 True 4 True dtype: bool </code></pre> <hr> <pre><code>df = df[cond1] df </code></pre> <p><a href="http://i.stack.imgur.com/YopRh.png" rel="nofollow"><img src="http://i.stack.imgur.com/YopRh.png" alt="enter image description here"></a></p> <p><strong><em>filter 2</em></strong><br> <code>groupby</code> <code>['email', 'call_date']</code> and get most recent with <code>idxmax</code></p> <pre><code>most_recent = df.groupby(['call_date', 'email']).signup_date.idxmax() most_recent call_date email 2016-05-04 b@b.com 4 2016-06-20 b@b.com 1 2016-07-25 a@a.com 0 Name: signup_date, dtype: int64 </code></pre> <p><strong><em>result</em></strong></p> <pre><code>df.ix[most_recent] </code></pre> <p><a href="http://i.stack.imgur.com/ZwZQW.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZwZQW.png" alt="enter image description here"></a></p> <hr> <p><strong><em>all together</em></strong></p> <pre><code>df = df1.merge(df2) cond1 = df.signup_date.le(df.call_date) df = df[cond1] most_recent = df.groupby(['call_date', 'email']).signup_date.idxmax() df.ix[most_recent] </code></pre> <p><a href="http://i.stack.imgur.com/ZwZQW.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZwZQW.png" alt="enter image description here"></a></p>
1
2016-10-04T06:44:29Z
[ "python", "pandas" ]
Finding first event in one table that occurred after event in a second table, per row
39,840,012
<p>I have a pandas DataFrame that looks like this:</p> <pre><code>email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16 </code></pre> <p>I have a second pandas DataFrame with related events, when a signup actually got followed through on, that looks like this:</p> <pre><code>email call_date a@a.com 7/25/16 b@b.com 6/20/16 b@b.com 5/4/16 </code></pre> <p>There are a few things to keep in mind. </p> <ul> <li>Some of the <code>signup_date</code>s may not have any later <code>call_date</code> for the corresponding email. That is, some people sign up but never get a call back.</li> <li>Some people signup more than once and get called after each signup.</li> <li>Some people signup more than once but don't get called after each signup.</li> <li>Some people signup more than once but may only get called after several signups. In this case we want to attribute the call to the most recent signup.</li> </ul> <p>Ultimately the goal is to determine whether there is a call event that came after a sign up event for a given user but before the next sign up event for the same user, where the number of signup events per user is not known in advance. </p> <p>Is there a <code>pandas</code> best practices way to do this? For now I'm using a for loop, and it's extremely slow (hasn't finished on 100,000 rows even after 20 minutes):</p> <pre><code>response_date = [] for i in range(signups.shape[0]): unique_id = signups.unique_id.values[i] start_date = signups.signup_date.values[i] end_date = signups.signup_date.values[-1] if end_date is start_date: end_date = end_date + pd.Timedelta('1 year') tmp_df = calls[calls.unique_id == unique_id] tmp_df = tmp_df[tmp_df.timestamp &gt; start_date][tmp_df.timestamp &lt; end_date] tmp_df = tmp_df.sort_values('timestamp') if tmp_df.shape[0] &gt; 0 : response_date.append(tmp_df.timestamp.values[0]) else: response_date.append(None) </code></pre> <p>Thanks for any advice!</p>
0
2016-10-03T20:38:50Z
39,846,934
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a>:</p> <pre><code>df = df1.merge(df2) df = df[df.signup_date &lt;= df.call_date] print (df.sort_values("signup_date", ascending=False) .groupby(['call_date', 'email'], as_index=False) .first()) call_date email signup_date 0 2016-05-04 b@b.com 2016-04-04 1 2016-06-20 b@b.com 2016-06-06 2 2016-07-25 a@a.com 2016-07-21 </code></pre>
1
2016-10-04T07:50:11Z
[ "python", "pandas" ]
Distance between point and a line (from two points)
39,840,030
<p>I'm using Python+Numpy (can maybe also use Scipy) and have three 2D points (P1, P2, P3); I am trying to get the distance from P3 perpendicular to a line drawn between P1 and P2. Call P1 (x1,y1), P2 (x2,y2) and P3 (x3,y3)</p> <p>In vector notation this would be pretty easy, but I'm fairly new to python/numpy and can't get anythng that works (or even close).</p> <p>Any tips appreciated, thanks!</p>
-2
2016-10-03T20:40:11Z
39,840,218
<p>Try using the <em>norm</em> function from <code>numpy.linalg</code></p> <pre><code>d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1) </code></pre>
0
2016-10-03T20:51:44Z
[ "python", "numpy", "vector", "scipy", "point" ]
Python code crashes with "cannot connect to X server" when detaching ssh+tmux session
39,840,184
<p>I run Python code on a remote machine (which I ssh into) and then use Tmux. The code runs fine UNTIL I disconnect from the remote machine. The whole point of my connecting via Tmux is so that the code continues to run even when I'm not connected to the remote machine. When I reconnect later, I have the error message:</p> <pre><code>: cannot connect to X server localhost:11.0 </code></pre> <p>Does anyone have an idea why this is happening or how I can stop it?</p>
0
2016-10-03T20:49:08Z
39,840,271
<pre><code>cannot connect to X server localhost:11.0 </code></pre> <p>...means that your code is trying (and failing) to connect to an X server -- a GUI environment -- presumably being forwarded over your SSH session. <code>tmux</code> provides session continuity for terminal applications; it can't emulate an X server.</p> <hr> <p>If you want to stop it from being able to make any GUI connection at all (and perhaps, if the software is thusly written, from even trying), unset the <code>DISPLAY</code> environment variable before running your code.</p> <p>If this causes an error or exception, the code generating that is the same code that's causing your later error.</p> <hr> <p>If you want to create a <strong>fake</strong> GUI environment that will still be present, you can do that too, with Xvfb.</p> <p>Some Linux distributions provide the <code>xvfb-run</code> wrapper, to automate setting this up for you:</p> <pre><code># prevent any future commands in this session from connecting to your real X environment unset DISPLAY XAUTHORITY # run yourcode.py with a fake X environment provided by xvfb-run xvfb-run python yourcode.py </code></pre> <p>By the way, see the question <a href="http://stackoverflow.com/questions/30332137/xvfb-run-unreliable-when-multiple-instances-invoked-in-parallel">xvfb-run unreliable when multiple instances invoked in parallel</a> for notes on a bug present in xvfb-run, and a fix available for same.</p> <hr> <p>If you want an X server you can actually detach from and reattach to later, letting you run GUI applications with similar functionality to what tmux gives you for terminal applications, consider using <a href="https://en.wikipedia.org/wiki/X11vnc" rel="nofollow">X11vnc</a> or a similar tool.</p>
1
2016-10-03T20:55:07Z
[ "python", "ssh", "tmux" ]
Azure deployment not installing Python packages listed in requirements.txt
39,840,209
<p>This is my first experience deploying a Flask web app to Azure. I followed this <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-create-deploy-flask-app/" rel="nofollow">tutorial</a>. </p> <p>The default demo app they have works fine for me. </p> <p>Afterwards, I pushed my Flask app via git. The log shows deployment was successful. However, when I browse the hosted app via link provided in "Application Properties", I get a 500 error as follows:</p> <blockquote> <p>The page cannot be displayed because an internal server error has occurred.</p> <p>Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the Web site or application. The authenticated user does not have permission to use this DLL. The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.</p> </blockquote> <p>The only off-base thing I can see by browsing the wwwroot via KUDU is that none of the packages I have installed in my local virtual environment are installed on Azure despite the existence of the "requirements.txt" file in wwwroot.</p> <p>My understanding is that Azure would pip install any non existent package that it finds in the requirements.txt upon GIT successful push. But it doesn't seem to be happening for me.</p> <p>Am I doing something wrong and the missing packages is just a symptom or could it be the cause the issue?</p> <p>Notes:</p> <ul> <li><p>My Flask app works fine locally (linux) and on a 3rd party VPS</p></li> <li><p>I redeployed several times starting from scratch to no avail (I use local GIT method)</p></li> <li><p>I cloned the Azure Flask demo app locally, changed just the app folder and pushed back to Azure, yet no success.</p></li> <li><p>Azure is set to Python 2.7 same as my virtual env locally</p></li> <li><p>As suggested in the tutorial linked above, I deleted the "env" folder and redeployed to trick Azure to reinstall the virtual env. It did but with its own default packages not the one in my requirements.txt.</p></li> </ul> <p>My requirements.txt has the following:</p> <blockquote> <p>bcrypt==3.1.0 cffi==1.7.0 click==6.6 Flask==0.11.1 Flask-Bcrypt==0.7.1 Flask-Login==0.3.2 Flask-SQLAlchemy==2.1 Flask-WTF==0.12 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 pycparser==2.14 PyMySQL==0.7.7 python-http-client==1.2.3 six==1.10.0 smtpapi==0.3.1 SQLAlchemy==1.0.14 Werkzeug==0.11.10 WTForms==2.1</p> </blockquote>
0
2016-10-03T20:50:58Z
39,845,489
<p>As Azure Web Apps will run a <code>deploy.cmd</code> script as the deployment task to control which commands or tasks will be run during the deployment. </p> <p>You can use the command of Azure-CLI <code>azure site deploymentscript --python</code> to get the python applications' deployment task script.</p> <p>And you can find the following script in this <code>deploy.cmd</code> sciprt:</p> <pre><code>IF NOT EXIST "%DEPLOYMENT_TARGET%\requirements.txt" goto postPython IF EXIST "%DEPLOYMENT_TARGET%\.skipPythonDeployment" goto postPython echo Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. </code></pre> <p>So the <code>.skipPythonDeployment</code> will skip all the following steps in deployment task, including creating virtual environment.</p> <p>You can try to remove <code>.skipPythonDeployment</code> from your application, and try again.</p> <p>Additionally, please refer to <a href="https://github.com/projectkudu/kudu/wiki/Custom-Deployment-Script" rel="nofollow">https://github.com/projectkudu/kudu/wiki/Custom-Deployment-Script</a> for more info.</p>
0
2016-10-04T06:26:34Z
[ "python", "azure", "deployment", "flask", "requirements.txt" ]
mesos configuration error in centos7
39,840,267
<p>I am trying to install mesos 1.0.1 on centos 7 but i am running into _FORTIFY_SOURCE error. Has anyone found a fix/workaround? It seems there is a patch but i don't know where to get it from. I'd appreciate any help with this. Thanks! <br> </p> <pre><code>checking whether we can build usable Python eggs... In file included from /usr/include/limits.h:26:0, from /usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.3.0/include-fixed/limits.h:168, from /usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.3.0/include-fixed/syslimits.h:7, from /usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.3.0/include-fixed/limits.h:34, from /usr/include/python2.7/Python.h:19, from testpyegg.cpp:1: /usr/include/features.h:330:4: warning: #warning _FORTIFY_SOURCE requires compiling with optimization (-O) [-Wcpp] warning _FORTIFY_SOURCE requires compiling with optimization (-O) configure: error: no </code></pre>
0
2016-10-03T20:54:54Z
40,096,918
<p>Adarsh, seems like your error comes from building the Python eggs. Could you paste the full error log, so that we can better help you to triage your issue. BTW, installing Mesos is straight forward. You are not expected to handle issues with <code>_FORTIFY_SOURCE</code> or <code>optimization</code>. Please follow this document to install Mesos on CentOS. <a href="http://mesos.apache.org/gettingstarted/" rel="nofollow">http://mesos.apache.org/gettingstarted/</a></p> <p>BTW, if you have any further question about Mesos, feel free to ask through Mesos mailing list: <a href="http://mesos.apache.org/community/" rel="nofollow">http://mesos.apache.org/community/</a> or Mesos slack channel: mesos-slackin.herokuapp.com/</p> <p>You will get more quick answers from the Mesos community there.</p> <p>Gilbert</p>
-1
2016-10-17T22:55:34Z
[ "python", "centos7", "mesos" ]
Using Python to parse pdf and extract Author and Book name
39,840,333
<p>I have a Mailing Reference List in a form a pdf. The mailing list has a very general format i.e Author Name followed by the Name of the book. Consider the following examples:</p> <p><strong>American Reading List</strong></p> <p><strong>Democratic Theory</strong></p> <p>• Dahl, Preface to Democratic Theory</p> <p>• Schumpeter, Capitalism, Socialism, and Democracy (Introduction and part IV only)</p> <p>• Machperson, Life and Times of Liberal Democracy</p> <p>• Dahl, Democracy and its Critics</p> <p>Now I am trying to parse the pdf using pdf miner and create a list where in the first index is the author name and the second index is the name of the book just like this:</p> <p>[Dahl, Preface to Democratic Theory]</p> <p>I am trying to use the split functionality because there is a comma and a space followed by the Author name. However I don't get the correct results. Can somebody help?</p> <pre><code>def extract(): string = convert_pdf_to_txt("/Users/../../names.pdf") lines = list(filter(bool, string.split('\n'))) for i in lines: check.extend(i.split(',')) x=remove_numbers(check) remove_blank= [x for x in x if x] combine_two = [remove_blank[x:x + 2] for x in xrange(0,len(remove_blank), 2)] print combine_two </code></pre>
0
2016-10-03T20:59:14Z
39,840,535
<p>Let's see what's going wrong here. I'm making some guesses, but hopefully they are the relevant ones.</p> <ol> <li>Your <code>convert_pdf_to_text()</code> function returns a single long string containing all the text of the PDF.</li> <li>You split the text on <code>", "</code> which results in a list of strings.</li> </ol> <p>Given your example data, this list looks something like this (each element is on a separate line here):</p> <pre><code>Dahl Preface to Democratic Theory(line break)(bullet)(tab)Schumpeter Captitalism Socialism and Democracy (Introduction and part IV only)(line break)(bullet)(tab)Machpherson Life and Times of Liberal Democracy(line break)(bullet)(tab)Dahl Democracy and its Critics </code></pre> <p>Because you split on <code>", "</code> without regard for the fact that the data is formatted as lines, you end up with stuff from multiple lines in each item.</p> <ol start="3"> <li>Now you use <code>filter()</code> to iterate over this list and filter out all the ones that aren't true. A non-empty string is true, and all of the elements are non-empty strings, so all the elements get through. Your <code>filter()</code> therefore doesn't do anything. </li> </ol> <p>What you seem to want is something more like this:</p> <pre><code>lines = [line.split(", ", 1) for line in string.splitlines() if ", " in line] </code></pre> <p>Here we first split the lines, filter out any that don't have comma-space in them, and return a list of lists based on splitting the string on the first comma-space.</p>
2
2016-10-03T21:16:04Z
[ "python", "pdf", "split" ]
ConnectionRefusedError: [Errno 111] Connection refused
39,840,357
<p>I was trying to use <code>ftp</code> and I am getting the following error:</p> <pre><code>&gt;&gt;&gt; ftp = ftplib.FTP('192.168.248.108') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.5/ftplib.py", line 118, in __init__ self.connect(host) File "/usr/lib/python3.5/ftplib.py", line 153, in connect source_address=self.source_address) File "/usr/lib/python3.5/socket.py", line 711, in create_connection raise err File "/usr/lib/python3.5/socket.py", line 702, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused </code></pre> <p>I was trying to take it step by step since the whole client and server codes were not running. Help please. Thank you.</p> <p><strong>EDIT:</strong><br> This is the client side code:</p> <pre><code>from ftplib import FTP ftp = FTP('192.168.248.128') ftp.login(user='username', passwd = 'password') ftp.cwd('/Desktop/FTP') def placeFile(): filename = 'myfile.txt' ftp.storbinary('STOR '+filename, open(filename, 'rb')) ftp.quit() placeFile() </code></pre>
0
2016-10-03T21:01:04Z
39,840,788
<p>First of all check this ip to see if <code>ftp</code> service is available, and if it is check the <code>port</code> that it is listening on, cause it maybe (rare but possible) is configured to listen on a different port than the standard one - <strong>21</strong> . Also maybe the connection is blocked by a <strong>firewall</strong>, and that is why connection gets refused. </p> <p>Also haven't seen the whole code of yours but I think another/different problem is this: <code>def placeFile()</code> should be changed to this instead <code>def placeFile(ftp)</code> - cause the function <code>placeFile</code> doesn't really know that <code>ftp</code> references to the ftp client you created above.</p>
0
2016-10-03T21:35:11Z
[ "python", "ftp" ]
How to convert one column's all values to separate column name in DataFrame of Pandas
39,840,377
<p>Sample data are as follows:</p> <pre><code>df = pd.DataFrame([(2011, 'a', 1.3), (2012, 'a', 1.4), (2013, 'a', 1.6), (2011, 'b', 0.7), (2012, 'b', 0.9), (2013, 'b', 1.2),], columns=['year', 'district', 'price']) df.set_index(['year'], inplace=True) df.head(n=10) </code></pre> <p>which could produce data like:</p> <pre><code> district price year 2011 a 1.3 2012 a 1.4 2013 a 1.6 2011 b 0.7 2012 b 0.9 2013 b 1.2 </code></pre> <p>What I intend to convert the DataFrame to is as below:</p> <pre><code> a b year 2011 1.3 0.7 2012 1.4 0.9 2013 1.6 1.2 </code></pre> <p>Could anyone give me some idea on how to do that? Great thanks!</p>
0
2016-10-03T21:02:17Z
39,840,429
<p>use pivot</p> <pre><code>In[122]: df.reset_index().pivot('year','district','price') Out[122]: district a b year 2011 1.3 0.7 2012 1.4 0.9 2013 1.6 1.2 </code></pre>
0
2016-10-03T21:06:49Z
[ "python", "pandas", "dataframe", "pivot" ]
Can I pass a file to Popen and still have it run asynchronously
39,840,484
<p>I have a Django based server and I'm calling a script which does a bunch of work. This needs to be asynchronous so I'm using Popen. However for debugging I want to redirect stdout and stderr from PIPE to a file. Will this affect the asynchronous performance?</p> <p>How should I make sure the file opens and closes properly when the python script itself is already done (and has made a return call.)</p>
0
2016-10-03T21:12:24Z
39,840,622
<p><code>Popen</code> runs asynchronously by default.</p> <p>The <code>Popen</code> object can be stored and queried later.</p> <pre><code>p = subproccess.Popen(executable) # continue with other work p.poll() # returns None if p is still running, returncode otherwise p.terminate() # closes the process forcefully p.wait() # freezes the execution until process finishes - makes it synchronous </code></pre> <p>All that is needed is to store <code>p</code> somewhere until its status has to be checked, e.g. in a global list of started processes, if there is no better place.</p> <p><strong>UPDATE</strong></p> <p>The problem seems to be how to open a file, give it to <code>Popen</code> and then close the file when the process is finished, without keeping any references.</p> <p>This can be simply done with a thread:</p> <pre><code>def run_process(executable, filename): with open(filename, 'w') as f: subprocess.Popen(executable, stdout=f).wait() Thread(target=run_process, args=(executable, filename)).start() </code></pre> <p>Run it and forget about it. <code>run_process</code> will freeze until the process finishes and then it will close the file, but that all happens in a different thread.</p> <p><strong>Note:</strong> you may or may not care about what happens to the thread or to the process if they are not finished when the django process finishes.</p> <p>For handling that, you might create a more complex thread which you would remember and stop when before django exits; it may also close the process or wait for it to finish...</p>
1
2016-10-03T21:22:49Z
[ "python", "asynchronous", "subprocess" ]
Can I pass a file to Popen and still have it run asynchronously
39,840,484
<p>I have a Django based server and I'm calling a script which does a bunch of work. This needs to be asynchronous so I'm using Popen. However for debugging I want to redirect stdout and stderr from PIPE to a file. Will this affect the asynchronous performance?</p> <p>How should I make sure the file opens and closes properly when the python script itself is already done (and has made a return call.)</p>
0
2016-10-03T21:12:24Z
39,840,658
<p>It depends on how asynchronous your program needs to be. Writes to stdout go to the operating system's file cache which is normally fast but may wait from time to time as data is flushed to the disk. Normally that's not a problem.</p> <p>Since stdout is not a console, it will do buffered writes and that can be a problem if the program hits a non-standard error that skips flushing the pipe. The buffering can also delay what is in the file so for instance an external program cat'ing the file may not see logs right away.</p> <p>The parent process should close its view of the file after starting the child and the operating system will take care of closing the file when the process terminates.</p> <pre><code>with open('stdout', 'w') as out, open('stderr', 'w') as err: proc = subprocess.Popen(['myprog'], stdout=out, stderr=err) </code></pre>
1
2016-10-03T21:25:38Z
[ "python", "asynchronous", "subprocess" ]
ValueError: shapes (2,2) and (4,6) not aligned: 2 (dim 1) != 4 (dim 0)
39,840,534
<p>Complaining about this line: </p> <pre><code>log_centers = pca.inverse_transform(centers) </code></pre> <p>Code:</p> <pre><code># TODO: Apply your clustering algorithm of choice to the reduced data clusterer = KMeans(n_clusters=2, random_state=0).fit(reduced_data) # TODO: Predict the cluster for each data point preds = clusterer.predict(reduced_data) # TODO: Find the cluster centers centers = clusterer.cluster_centers_ log_centers = pca.inverse_transform(centers) </code></pre> <p>Data:</p> <pre><code>log_data = np.log(data) good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True) pca = PCA(n_components=2) pca = pca.fit(good_data) reduced_data = pca.transform(good_data) reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2']) </code></pre> <p>data is a csv; header looks like:</p> <pre><code> Fresh Milk Grocery Frozen Detergents_Paper Delicatessen 0 14755 899 1382 1765 56 749 1 1838 6380 2824 1218 1216 295 2 22096 3575 7041 11422 343 2564 </code></pre>
0
2016-10-03T21:16:00Z
39,847,481
<p>The problem is that <code>pca.inverse_transform()</code>should not take <code>clusters</code>as argument.</p> <p>Indeed, if you look at the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA.inverse_transform" rel="nofollow">documentation</a>, it should take the <strong>data</strong> obtained from the PCA <strong>applied to your original data</strong> and <strong>not</strong> the <strong>centroids</strong> obtained with KMeans.</p>
0
2016-10-04T08:22:44Z
[ "python", "scikit-learn", "pca", "sklearn-pandas" ]
Must produce aggregated value. I swear that I am
39,840,546
<p>consider the <code>pd.Series</code> <code>s</code></p> <pre><code>a = np.arange(4) mux = pd.MultiIndex.from_product([list('ab'), list('xy')]) s = pd.Series([a] * 4, mux) print(s) a x [0, 1, 2, 3] y [0, 1, 2, 3] b x [0, 1, 2, 3] y [0, 1, 2, 3] dtype: object </code></pre> <hr> <p><strong><em>problem</em></strong><br> each element of <code>s</code> is a <code>numpy.array</code>. when I try to sum within groups, I get an error because the groupby function expects the result to be scalar... (I'm guessing)</p> <pre><code>s.groupby(level=0).sum() </code></pre> <blockquote> <pre><code>Exception Traceback (most recent call last) &lt;ipython-input-627-c5b3bf6890ea&gt; in &lt;module&gt;() ----&gt; 1 s.groupby(level=0).sum() C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in f(self) 101 raise SpecificationError(str(e)) 102 except Exception: --&gt; 103 result = self.aggregate(lambda x: npfunc(x, axis=self.axis)) 104 if _convert: 105 result = result._convert(datetime=True) C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in aggregate(self, func_or_funcs, *args, **kwargs) 2584 return self._python_agg_general(func_or_funcs, *args, **kwargs) 2585 except Exception: -&gt; 2586 result = self._aggregate_named(func_or_funcs, *args, **kwargs) 2587 2588 index = Index(sorted(result), name=self.grouper.names[0]) C:\Anaconda2\lib\site-packages\pandas\core\groupby.pyc in _aggregate_named(self, func, *args, **kwargs) 2704 output = func(group, *args, **kwargs) 2705 if isinstance(output, (Series, Index, np.ndarray)): -&gt; 2706 raise Exception('Must produce aggregated value') 2707 result[name] = self._try_cast(output, group) 2708 Exception: Must produce aggregated value </code></pre> </blockquote> <hr> <p><strong><em>work around</em></strong><br> when I use <code>apply</code> with <code>np.sum</code>, it works fine.</p> <pre><code>s.groupby(level=0).apply(np.sum) a [0, 2, 4, 6] b [0, 2, 4, 6] dtype: object </code></pre> <hr> <p><strong><em>question</em></strong><br> is there an elegant way to handle this?</p> <hr> <p><strong><em>real problem</em></strong><br> I actually want to use <code>agg</code> in this way</p> <pre><code>s.groupby(level=0).agg(['sum', 'prod']) </code></pre> <p>but it fails in the same way.<br> the only way to get this is to</p> <pre><code>pd.concat([g.apply(np.sum), g.apply(np.prod)], axis=1, keys=['sum', 'prod']) </code></pre> <p><a href="http://i.stack.imgur.com/1108f.png" rel="nofollow"><img src="http://i.stack.imgur.com/1108f.png" alt="enter image description here"></a></p> <p>but this doesn't generalize well to longer lists of transforms.</p>
0
2016-10-03T21:16:29Z
39,842,473
<p><a href="http://stackoverflow.com/questions/16975318/pandas-aggregate-when-column-contains-numpy-arrays">from this well explained answer</a> you could transform your ndarray to list because pandas seems to be checking if the output is a ndarray and this is why you are getting this error raised :</p> <pre><code>s.groupby(level=0).agg({"sum": lambda x: list(x.sum()), "prod":lambda x: list(x.prod())}) </code></pre> <p>Out[249]: </p> <pre><code> sum prod a [0, 2, 4, 6] [0, 1, 4, 9] b [0, 2, 4, 6] [0, 1, 4, 9] </code></pre>
1
2016-10-04T00:30:28Z
[ "python", "pandas" ]
Tweepy Get List of Favorites for a Specific User
39,840,571
<p>I am attempting to get a list of favorited tweets made by a specific user. Their twitter account indicates that they have favorited nearly 20k tweets but the list of favorites being returned through the API is only ~2,300 favorited tweets. Below is a sample of my python code:</p> <pre><code>api = tweepy.API(auth) test_user = "someuser" #print out each favorited tweet for page in tweepy.Cursor(api.favorites,id=test_user,wait_on_rate_limit=True, count=200).pages(200): for status in page: print status.user.screen_name.encode('utf-8') + ": " + status.text.encode('utf-8') </code></pre> <p>I assumed that the count = 200 and pages = 200 would give me 40,000 tweets max. Am I missing something?</p>
0
2016-10-03T21:18:56Z
39,840,991
<p>From a bit more digging on the twitter API, it looks like there is a cap on the number of tweets we can query. See <a href="https://twittercommunity.com/t/tweet-index-limits/49653" rel="nofollow">this question</a> from the twitter developer forum.</p>
0
2016-10-03T21:52:48Z
[ "python", "api", "twitter", "tweepy" ]
SyntaxError: invalid syntax with Chicken coop door script
39,840,615
<p>I am new to python, I have been trying to get a piece of code working to control a chicken coop door. The github link is <a href="https://github.com/ryanrdetzel/CoopControl" rel="nofollow">https://github.com/ryanrdetzel/CoopControl</a></p> <p>The problem I have is that if I run server.py it does not get the MAILGUN_KEY variable from the coop.conf file. So I tried running start.sh I get SyntaxError: invalid syntax error, but I can not see for the life of me what can be wrong.</p> <p>This is the start.sh file</p> <p><code>sudo MAILGUN_KEY = 'key-c5e6aa4561a7077e8c0fc55e594cf26' MAILGUN_URL = 'https://api.mailgun.net/v3/sandboxc1ea9c71ab95485dac75b03cc5dd5883.mailgun.org/messages' MAILGUN_RECIPIENT = 'google@google.org' python server.py</code></p> <p>The Syntax error is under the <code>Y</code> of <code>MAILGUN_KEY</code>, I am running python verson 3. I don't know if that would make a difference. </p> <p>Can anyone see the problem?</p>
-1
2016-10-03T21:22:19Z
39,840,741
<p>You are mixing up shell script syntax and Python syntax. Your problem is not at all related to Python.</p> <p>To set environment variables for single invocation of binary, correct form is:</p> <pre class="lang-sh prettyprint-override"><code>ENV1=VAL1 ENV2=VAL2 /path/to/bin some args </code></pre> <p>So in your case it would be:</p> <pre class="lang-sh prettyprint-override"><code>MAILGUN_KEY=key-c5e6aa4561a7077e8c0fc55e594cf26 MAILGUN_URL=https://api.mailgun.net/v3/sandboxc1ea9c71ab95485dac75b03cc5dd5883.mailgun.org/messages MAILGUN_RECIPIENT=google@google.org sudo python server.py </code></pre>
1
2016-10-03T21:31:44Z
[ "python", "syntax-error", "sh" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matched up with. So far I've only been able to "extract" the first and last letter of the whole string and not each individual word. I know I'm meant to convert the string into a list, but I'm not entirely sure how to go about it. Any help would be greatly appreciated. Thanks!</p> <pre><code>def get_text_value(text): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] text_value = 0 text = text.lower() for i in text: if text[0] and text[-1] in letters: letters_index_1 = letters.index(text[0]) letters_index_2 = letters.index(text[-1]) text_value = letter_values[letters_index_1] + letter_values[letters_index_2] return text_value def test_get_text_value(): print("1. Text value:", get_text_value("abracadabra")) print("2. Text value:", get_text_value("a b")) print("3. Text value:", get_text_value("enjoy Today")) print("4. Text value:", get_text_value("")) text = "Be yourself everyone else is already taken" text_value = get_text_value(text) print("6. Text:", text) print("6. Text value:", text_value) </code></pre>
2
2016-10-03T21:23:00Z
39,840,755
<p>First of all: store the values in a dictionary, that's way less work.</p> <p>Then, just iterate over the words in the text and add the values:</p> <pre><code>def get_text_value(text): lv = {'a': 1, 'b': 4, 'c': 2, 'd': 3, 'e': 1, 'f': 4, 'g': 3, 'h': 4, 'i': 1, 'j': 7, 'k': 7, 'l': 4, 'm': 6, 'n': 6, 'o': 1, 'p': 3, 'q': 9, 'r': 2, 's': 2, 't': 2, 'u': 1, 'v': 8, 'w': 5, 'x': 9, 'y': 9, 'z': 9} return sum( lv.get(word[:1], 0) + lv.get(word[-1:], 0) for word in text.lower().split(" ") ) </code></pre>
0
2016-10-03T21:32:49Z
[ "python", "string", "list", "python-3.x" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matched up with. So far I've only been able to "extract" the first and last letter of the whole string and not each individual word. I know I'm meant to convert the string into a list, but I'm not entirely sure how to go about it. Any help would be greatly appreciated. Thanks!</p> <pre><code>def get_text_value(text): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] text_value = 0 text = text.lower() for i in text: if text[0] and text[-1] in letters: letters_index_1 = letters.index(text[0]) letters_index_2 = letters.index(text[-1]) text_value = letter_values[letters_index_1] + letter_values[letters_index_2] return text_value def test_get_text_value(): print("1. Text value:", get_text_value("abracadabra")) print("2. Text value:", get_text_value("a b")) print("3. Text value:", get_text_value("enjoy Today")) print("4. Text value:", get_text_value("")) text = "Be yourself everyone else is already taken" text_value = get_text_value(text) print("6. Text:", text) print("6. Text value:", text_value) </code></pre>
2
2016-10-03T21:23:00Z
39,844,035
<p>Looks like you're just getting started with Python. Welcome! Couple things that might be worth getting more familiar with.</p> <ol> <li>Dictionaries</li> </ol> <p>Dictionaries are good for storing a key value pair. In your case, a dictionary would work really well as you have a letter (your key) and a numerical value (the value). As mentioned in the other answer, a dictionary is going to significantly clean up your code.</p> <ol start="2"> <li>String methods.</li> </ol> <p>The function you need to go from getting the first and last letter of the entire sentence to the first and last of each word is <code>split</code>. It will split one string into a list of strings where it finds a space.</p> <pre><code>&gt;&gt;&gt; "enjoy Today".split(" ") ['enjoy', 'Today'] &gt;&gt;&gt; "abracadabra".split(" ") ['abracadabra'] </code></pre> <p>You don't have to just split on spaces.</p> <pre><code>&gt;&gt;&gt; "abracadabra".split("b") ['a', 'racada', 'ra'] </code></pre> <ol start="3"> <li>List comprehension</li> </ol> <p>Just google it as there are lots of articles that will do a better job explaining then I will here.</p> <p>These 3 methods are a few of the key building blocks that will make Python enjoyable to write and your code concise and easy to read.</p>
0
2016-10-04T04:10:19Z
[ "python", "string", "list", "python-3.x" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matched up with. So far I've only been able to "extract" the first and last letter of the whole string and not each individual word. I know I'm meant to convert the string into a list, but I'm not entirely sure how to go about it. Any help would be greatly appreciated. Thanks!</p> <pre><code>def get_text_value(text): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] text_value = 0 text = text.lower() for i in text: if text[0] and text[-1] in letters: letters_index_1 = letters.index(text[0]) letters_index_2 = letters.index(text[-1]) text_value = letter_values[letters_index_1] + letter_values[letters_index_2] return text_value def test_get_text_value(): print("1. Text value:", get_text_value("abracadabra")) print("2. Text value:", get_text_value("a b")) print("3. Text value:", get_text_value("enjoy Today")) print("4. Text value:", get_text_value("")) text = "Be yourself everyone else is already taken" text_value = get_text_value(text) print("6. Text:", text) print("6. Text value:", text_value) </code></pre>
2
2016-10-03T21:23:00Z
39,844,229
<p>do like this:</p> <pre><code>def get_text_value2(text): letters = [chr(i) for i in range(ord('a'), ord('z')+1)] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] alpha_value_dict = dict(zip(letters, letter_values)) formatted_text = text.lower() return alpha_value_dict.get(text[0], 0) + alpha_value_dict.get(text[-1], 0) </code></pre> <p>or if you want keep the same logic of return value with your origional function, you can do:</p> <pre><code>def get_text_value2(text): letters = [chr(i) for i in range(ord('a'), ord('z')+1)] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] alpha_value_dict = dict(zip(letters, letter_values)) formatted_text = text.lower() try: return alpha_value_dict[text[0]] + alpha_value_dict[text[-1]] except: return 0 </code></pre>
0
2016-10-04T04:35:34Z
[ "python", "string", "list", "python-3.x" ]
Launch Python script in new terminal
39,840,632
<p>I want to launch a python script in a new macOS terminal window from another script. I'm currently using this code:</p> <pre><code>subprocess.call(['open', '-a', 'Terminal.app', '/usr/bin/python']) </code></pre> <p>which launches a python prompt in a new terminal window. But when I try to run a python script with this code:</p> <pre><code>subprocess.call(['open', '-a', 'Terminal.app', '/usr/bin/python', 'test.py']) </code></pre> <p>it completely ignores the <code>'test.py'</code> on the end and starts a python prompt, just like it does without the test.py on the end.</p> <p>How can I make this work?</p>
0
2016-10-03T21:23:22Z
39,840,688
<p>Don't use the <code>open -a terminal.app</code>, just use the python executable</p> <pre><code>subprocess.call(['/usr/bin/python', 'test.py']) </code></pre>
0
2016-10-03T21:27:52Z
[ "python", "osx", "python-2.7", "subprocess", "terminal.app" ]
Parsing pyparsing group of mixed character words
39,840,633
<p>I'm trying to parse data fields from a Wikipedia infobox using pyparsing. To start with, the following code works:</p> <pre><code>from pyparsing import * test_line = """{{Infobox company | name = Exxon Mobil Corp | num_employees_year = 2015 }}""" data_group = Group( Suppress("|") + OneOrMore(White()).suppress() + Word(alphanums + printables)("key") + OneOrMore(White()).suppress() + Suppress("=") + OneOrMore(White()).suppress() + OneOrMore(Word(alphanums))("value") + ZeroOrMore(White()).suppress() ) infobox_parser = ( Literal("{{").suppress() + Word("Infobox") + White().suppress() + Word("company") + OneOrMore(White()).suppress() + OneOrMore(data_group)("values") + Literal("}}").suppress() ) print(infobox_parser.parseString(test_line)) </code></pre> <p>Which produces result:</p> <pre><code>['Infobox', 'company', ['name', 'Exxon', 'Mobil', 'Corp'], ['num_employees_year', '2015']] </code></pre> <p>The problem is when I change the test string to</p> <pre><code>test_line = """{{Infobox company | name = Exxon Mobil Corp. | num_employees_year = 2015 }}""" </code></pre> <p>It's failing because I introduced '.' as part of 'Corp.'. I thought I could fix this by changing the Group object to</p> <pre><code>data_group = Group( Suppress("|") + OneOrMore(White()).suppress() + Word(alphanums + printables)("key") + OneOrMore(White()).suppress() + Suppress("=") + OneOrMore(White()).suppress() + OneOrMore(Word(alphanums + printables))("value") + ZeroOrMore(White()).suppress() ) </code></pre> <p>but I'm getting the following error:</p> <pre><code>pyparsing.ParseException: Expected "}}" (at char 91), (line:1, col:92) </code></pre> <p>What am I missing here? Thanks in advance.</p>
1
2016-10-03T21:23:37Z
39,841,822
<p>Just a couple of things. Most significantly, pyparsing does not do the same kind of backtracking the way regex does. That is, something like this won't work:</p> <pre><code>data = '{' + OneOrMore(Word(printables))("data") + '}' print(data.parseString('{ this is some data }')) </code></pre> <p>Why? Because the terminating '}' <em>also</em> matches as a <code>Word(printables)</code>, so the <code>OneOrMore</code> will just keep going until the end, and then fail because there is no terminating '}' to be found after reading data.</p> <p>Up until recently, the solution was to include a guard inside the <code>OneOrMore</code> expression, a negative lookahed saying in effect "I want Word(printables), but first check if it's a '}' - I don't want that", and that looks like this:</p> <pre><code>data = '{' + OneOrMore(~Literal('}') + Word(printables))("data") + '}' </code></pre> <p>But this was so common, that I recently added an optional <code>stopOn</code> argument to <code>ZeroOrMore</code> and <code>OneOrMore</code>:</p> <pre><code>data = '{' + OneOrMore(Word(printables), stopOn=Literal('}'))("data") + '}' </code></pre> <p>In your case, where each data_group parses a <code>key=value</code> pair, your value was fine when you only parsed <code>OneOrMore(Word(alphanums))</code>. But once you changed it to <code>OneOrMore(Word(alphanums+printables))</code>, your repetition term would greedily match the next '|' or the terminating '}}', and fail just like the example above.</p> <p>A couple of other items:</p> <ul> <li><p>pyparsing will skip whitespace for you. All those White() elements are completely unnecessary.</p></li> <li><p>In a couple of places you use Word incorrectly, as in <code>Word("Infobox")</code>. In your limited example, this matches ok, but remember that Word is defined with the set of characters that you will want to match as a word group, so <code>Word("Infobox")</code> will match not only "Infobox", but also any other word made up of the letters 'I', 'n', 'f', 'o', 'b', and/or 'x', such as "Inbox", "IbIx", "xoxoxox", etc. In this case, the pyparsing class you want would be <code>Literal</code> or <code>Keyword</code>.</p></li> <li><p>Stepping back, it looks like your data_groups are <code>key=value</code> pairs, with delimiting '|'s. I would suggest using <code>delimitedList</code> for this.</p></li> <li><p>Finally, use <code>dump()</code> to output your parsed data, it will help visualize the structure and results names.</p></li> </ul> <p>With these changes, your code looks like:</p> <pre><code>data_group = Group( Word(alphas, alphanums+'_')("key") + Suppress("=") + originalTextFor(OneOrMore(Word(printables), stopOn=Literal('|') | '}}'))("value") ) infobox_parser = ( Literal("{{").suppress() + Keyword("Infobox") + Keyword("company") + '|' + Group(delimitedList(data_group, '|'))("values") + Literal("}}").suppress() ) print(infobox_parser.parseString(test_line).dump()) </code></pre> <p>Giving:</p> <pre><code>['Infobox', 'company', '|', [['name', 'Exxon Mobil Corp.'], ['num_employees_year', '2015']]] - values: [['name', 'Exxon Mobil Corp.'], ['num_employees_year', '2015']] [0]: ['name', 'Exxon Mobil Corp.'] - key: name - value: Exxon Mobil Corp. [1]: ['num_employees_year', '2015'] - key: num_employees_year - value: 2015 </code></pre>
1
2016-10-03T23:12:38Z
[ "python", "pyparsing" ]
Update mayavi plot in loop
39,840,638
<p>What I want to do is to update a mayavi plot in a loop. I want the updating of the plot to be done at a time specified by me (unlike, e.g., the animation decorator).</p> <p>So an example piece of code I would like to get running is:</p> <pre><code>import time import numpy as np from mayavi import mlab V = np.random.randn(20, 20, 20) s = mlab.contour3d(V, contours=[0]) for i in range(5): time.sleep(1) # Here I'll be computing a new V V = np.random.randn(20, 20, 20) # Update the plot with the new information s.mlab_source.set(scalars=V) </code></pre> <p>However, this doesn't display a figure. If I include <code>mlab.show()</code> in the loop, then this steals the focus and doesn't allow the code to continue.</p> <p>I feel what I should be using is a <em>traits</em> figure (e.g. <a href="http://docs.enthought.com/mayavi/mayavi/building_applications.html" rel="nofollow">this</a>). I can follow the example traits application to run a figure which live-updates as I update the sliders. However, I can't get it to update when my code asks it to update; the focus now is 'stolen' by <code>visualization.configure_traits()</code>.</p> <p>Any pointers, or a link to appropriate documentation, would be appreciated.</p> <hr> <p><strong>EDIT</strong></p> <p>David Winchester's answer gets a step closer to the solution. </p> <p>However, as I point out in the comments, I am not able to manipulate the figure with the mouse during the <code>time.sleep()</code> step. It is during this step that, in the full program, the computer will be busy computing the new value of V. During this time I would like to be able to manipulate the figure, rotating it with the mouse etc.</p>
2
2016-10-03T21:24:05Z
39,982,817
<p>I thin Mayavi uses <code>generators</code> to animate data. This is working for me:</p> <pre><code>import time import numpy as np from mayavi import mlab f = mlab.figure() V = np.random.randn(20, 20, 20) s = mlab.contour3d(V, contours=[0]) @mlab.animate(delay=10) def anim(): i = 0 while i &lt; 5: time.sleep(1) s.mlab_source.set(scalars=np.random.randn(20, 20, 20)) i += 1 yield anim() </code></pre> <p>I used this post as reference ( <a href="http://stackoverflow.com/questions/14287185/animating-a-mayavi-points3d-plot">Animating a mayavi points3d plot</a> )</p>
1
2016-10-11T17:07:30Z
[ "python", "interactive", "mayavi" ]
Update mayavi plot in loop
39,840,638
<p>What I want to do is to update a mayavi plot in a loop. I want the updating of the plot to be done at a time specified by me (unlike, e.g., the animation decorator).</p> <p>So an example piece of code I would like to get running is:</p> <pre><code>import time import numpy as np from mayavi import mlab V = np.random.randn(20, 20, 20) s = mlab.contour3d(V, contours=[0]) for i in range(5): time.sleep(1) # Here I'll be computing a new V V = np.random.randn(20, 20, 20) # Update the plot with the new information s.mlab_source.set(scalars=V) </code></pre> <p>However, this doesn't display a figure. If I include <code>mlab.show()</code> in the loop, then this steals the focus and doesn't allow the code to continue.</p> <p>I feel what I should be using is a <em>traits</em> figure (e.g. <a href="http://docs.enthought.com/mayavi/mayavi/building_applications.html" rel="nofollow">this</a>). I can follow the example traits application to run a figure which live-updates as I update the sliders. However, I can't get it to update when my code asks it to update; the focus now is 'stolen' by <code>visualization.configure_traits()</code>.</p> <p>Any pointers, or a link to appropriate documentation, would be appreciated.</p> <hr> <p><strong>EDIT</strong></p> <p>David Winchester's answer gets a step closer to the solution. </p> <p>However, as I point out in the comments, I am not able to manipulate the figure with the mouse during the <code>time.sleep()</code> step. It is during this step that, in the full program, the computer will be busy computing the new value of V. During this time I would like to be able to manipulate the figure, rotating it with the mouse etc.</p>
2
2016-10-03T21:24:05Z
40,025,839
<p>If you use the <code>wx</code> backend, you can call <code>wx.Yield()</code> periodically if you want to interact with your data during some long-running function. In the following example, <code>wx.Yield()</code> is called for every iteration of some "long running" function, <code>animate_sleep</code>. In this case, you could start the program with <code>$ ipython --gui=wx &lt;program_name.py&gt;</code></p> <pre><code>import time import numpy as np from mayavi import mlab import wx V = np.random.randn(20, 20, 20) f = mlab.figure() s = mlab.contour3d(V, contours=[0]) def animate_sleep(x): n_steps = int(x / 0.01) for i in range(n_steps): time.sleep(0.01) wx.Yield() for i in range(5): animate_sleep(1) V = np.random.randn(20, 20, 20) # Update the plot with the new information s.mlab_source.set(scalars=V) </code></pre>
1
2016-10-13T16:02:07Z
[ "python", "interactive", "mayavi" ]
Add threads to a Sudoku checker
39,840,676
<p>I have just created a simple function in Python which checks whether or not a Sudoku board (input is given as a list) is valid or not. The way I did it is pretty straight forward:</p> <ul> <li><p>check if the sudoku board is 9x9</p></li> <li><p>check that each number appears only once per row</p></li> <li>check that each number appears only once per column</li> <li>check that each number appears exactly once per 3x3 grid </li> </ul> <p>Now, once I started this, I wanted to take advantage and learn a bit about Python threads. I read the docs, and also some awesome general multithreading related posts here on SO, but I just couldn't think of a way of implementing them in my checker.</p> <p>Now, the way I'd like the threads works (as I thought) is one thread to check that each column contains 1-9 digits, another one to check the lines for the same thing, and another nine threads to check each 3x3 sub-grid. Could you guys please tell me (eventually with some explanations) how I could achieve this ? Thanks</p>
0
2016-10-03T21:26:55Z
39,843,103
<p>So to give some general pointers on how to achieve this, without taking away any challenge. Lets start by import Threading:</p> <pre><code>import threading </code></pre> <p>Which will let us use thread objects! Also, in order to know if the Sudoku grid will be valid after the fact, we need a variable to store the True/False condition in. You can either go for a single variable, and use Thread Locks to ensure no other threads access it at the same time, or go with three separate. For simplicity, I'll use three separate variables in this example</p> <pre><code>LinesValid = False ColumnsValid = False GridsValid = False </code></pre> <p>Then, since threads require a function or another callable to run as their target, and you desire a thread for columns, rows and for each 3x3 grid, we need three functions for each thread. However, since there are 9 columns, 9 rows and also 9 grids I believe it would be a lot better to just do a single thread for the grids as well, but for the purpose of the exercise I suppose it is fine to do one for each.</p> <pre><code>def CheckLines(): # Line Checking Code def CheckColumns(): # ColumnCheckingCode def CheckGrid(UpperLeft, BottomRight): # GridCheckingCode </code></pre> <p>Anyway, here we define our three functions, with their appropriate line checking code. Like the lines would check the X axis, and the Columns the Y axis, but the idea is to split it up. For the CheckGrid you would need to specify corners if you want it to have a thread for each tile, or if you decide on a single thread you would just define it as:</p> <pre><code>def CheckGrid(): # GridCheckingCode </code></pre> <p>After that we need to make our Threads:</p> <pre><code>LineThread = threading.Thread(target=CheckLines) ColumnThread = threading.Thread(target=CheckLines) GridThread = threading.Thread(target=CheckLines, args=([0, 0], [2, 2])) </code></pre> <p>You can ignore the arguments from the GridThread if you do not need the grids. Otherwise you need to specify corners, and find a way to loop through the specified tiles.</p> <p>After that it is a matter of starting the threads, and joining them with the main thread, before showing the data to the user:</p> <pre><code>LineThread.start() ColumnThread.start() GridThread.start() LineThread.join() ColumnThread.join() GridThread.join() if sum(LinesValid, ColumnsValid, GridsValid) == 3: print("The grid is valid!") else: print("The grid is invalid!") </code></pre> <p>Here we check if all our Bools are True: <code>( 1 + 1 + 1 ) == 3</code> if they are, and print data to the user based on this. These bools would be set to True/False within their respective Check** functions!</p> <p>If you desire some more direct solutions, rather than a general direction with explanations, please let me know and I'll throw something together! The final piece of code looks something like this:</p> <pre><code>import threading def CheckLines(self): # Line Checking Code def CheckColumns(self): # ColumnCheckingCode def CheckGrid(self, UpperLeft, BottomRight): # GridCheckingCode LinesValid = False ColumnsValid = False GridsValid = False LineThread = threading.Thread(target=CheckLines) ColumnThread = threading.Thread(target=CheckLines) GridThread = threading.Thread(target=CheckLines, args=([0, 0], [2, 2])) LineThread.start() ColumnThread.start() GridThread.start() LineThread.join() ColumnThread.join() GridThread.join() if sum(LinesValid, ColumnsValid, GridsValid) == 3: print("The grid is valid!") else: print("The grid is invalid!") </code></pre>
2
2016-10-04T02:00:52Z
[ "python", "multithreading", "python-3.x" ]
AttributeError: '<class 'praw.objects.MoreComments'>' has no attribute 'body'
39,840,686
<p>How can I fix this error?</p> <pre><code>import praw subreddit_name = 'relationships' num_submissions = 30 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top_submissions = subreddit.get_top_from_year(limit = num_submissions) for submission in top_submissions: all_comments = praw.helpers.flatten_tree(submission.comments) submission.replace_more_comments(limit=None, threshold=0) if len(all_comments) &gt; 100: print(len(all_comments)) #top_comments = all_comments.sort(key = lambda comment : comment.score, reverse = True) for comment in all_comments[:100]: print(comment.body) else: continue </code></pre> <p>I get:</p> <pre><code>Your mother would be very proud of you, you did an awesome job. Good luck with you and your father's therapy. [removed] [removed] Traceback (most recent call last): File "getSubmissionsFromSubreddit.py", line 16, in &lt;module&gt; print(comment.body) File "/usr/local/lib/python2.7/dist-packages/praw/objects.py", line 92, in __getattr__ raise AttributeError(msg) AttributeError: '&lt;class 'praw.objects.MoreComments'&gt;' has no attribute 'body' </code></pre>
0
2016-10-03T21:27:48Z
39,841,039
<p>stupid mistake but should have had <code>submission.replace_more_comments(limit=None, threshold=0)</code> above <code>all_comments = praw.helpers.flatten_tree(submission.comments)</code> line:</p> <pre><code>import praw subreddit_name = 'nostalgia' num_submissions = 2 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top_submissions = subreddit.get_top_from_year(limit = num_submissions, comment_sort='top') for submission in top_submissions: submission.replace_more_comments(limit=None, threshold=0) all_comments = praw.helpers.flatten_tree(submission.comments) if len(all_comments) &gt; 100: print(len(all_comments) all_comments = praw.helpers.flatten_tree(submission.comments)) #top_comments = all_comments.sort(key = lambda comment : comment.score, reverse = True) for comment in all_comments[:10]: print(comment.body) else: continue </code></pre>
0
2016-10-03T21:57:33Z
[ "python", "attributeerror", "reddit", "praw", "reddit-api" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't want to maintain 2 streams of code, one for web and another one for terminal.</p>
1
2016-10-03T21:31:23Z
39,840,766
<p>Just ask!</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; os.isatty(sys.stdin.fileno()) True </code></pre> <p>if true, you are attached to a console.</p>
1
2016-10-03T21:33:40Z
[ "python", "django" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't want to maintain 2 streams of code, one for web and another one for terminal.</p>
1
2016-10-03T21:31:23Z
39,844,217
<p>Why not use <code>__main__</code>: <a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">https://docs.python.org/3/library/<strong>main</strong>.html</a></p> <pre><code>if __name__ == '__main__': print ('running as a script') else: print ('running as a web app') </code></pre> <p>Works on both python 2.7 and 3.x Also see: <a class='doc-link' href="http://stackoverflow.com/documentation/django/5848/django-from-the-command-line/20596/django-from-the-command-line#t=201610040433419117038">Django from the command line.</a></p>
1
2016-10-04T04:34:07Z
[ "python", "django" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't want to maintain 2 streams of code, one for web and another one for terminal.</p>
1
2016-10-03T21:31:23Z
39,844,257
<p>Explicit is better than implicit. Wrap your interactivity in a function that's called only if the <code>__name__ == "__main__"</code> part was executed. From the django parts, just use it as a library. Most ways of doing these kinds of checks are semi-magical and hence flaky.</p>
0
2016-10-04T04:38:54Z
[ "python", "django" ]
Call module.Functionname from user input
39,840,807
<p>I'm trying to call module(.)functionname from a image lirary upon user input. For instance a user types in "GaussianBlurr"</p> <p>I want to be able to replace (<em>ImagerFilter.user_input</em>) and call that filter.(Line 3)</p> <pre><code>def ImageFilterUsingPil(): im = Image.open('hotdog.jpg') im.filter(ImageFilter.GaussianBlur) # instead im.filter(ImageFilter.user_input) im.save('hotdog.png') </code></pre> <p>Also I tried this</p> <pre><code>user_input = 'GaussianBlur' def ImageFilterUsingPil(): im = Image.open('hotdog.jpg') im.filter(ImageFilter.user_input) im.save('hotdog.png') </code></pre> <p>it threw me <code>AttributeError: 'module' object has no attribute 'user_input'</code></p>
0
2016-10-03T21:36:58Z
39,840,876
<p>You are looking to use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow">getattr</a> here. </p> <pre><code>call = getattr(ImageFilter, user_input) call() </code></pre> <p>More explicit to your code, you can do this: </p> <pre><code>im.filter(getattr(ImageFilter, user_input)()) </code></pre> <p>Simple example: </p> <pre><code>&gt;&gt;&gt; class Foo: ... @classmethod ... def bar(cls): ... print('hello') ... &gt;&gt;&gt; getattr(Foo, 'bar')() hello </code></pre> <p>However, you might want to make sure you handle exceptions for when you send something invalid. So, you should probably wrap your attempt to call the method with a <code>try/except</code>. </p> <pre><code>&gt;&gt;&gt; try: ... getattr(Foo, 'bar')() ... except AttributeError: ... # do exception handling here </code></pre> <p>You could also assign a default as <code>None</code> (Personally I would rather (<a href="http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python">EAFP</a>) and then check to see if it is not <code>None</code> before calling it: </p> <pre><code>call = getattr(ImageFilter, user_input, None) if call: call() else: # do fail logic here </code></pre>
0
2016-10-03T21:42:36Z
[ "python", "function" ]
Exiting a tkinter app with Ctrl-C and catching SIGINT
39,840,815
<p>Ctrl-C/SIGTERM/SIGINT seem to be ignored by tkinter. Normally it can be <a href="http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python">captured again with a callback</a>. This doesn't seem to be working, so I thought I'd run tkinter <a href="http://stackoverflow.com/a/1835036/1888983">in another thread</a> since its <a href="http://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop">mainloop() is an infinite loop and blocks</a>. I actually also want to do this to read from stdin in a separate thread. Even after this, Ctrl-C is still not processed until I close the window. Here's my MWE:</p> <pre><code>#! /usr/bin/env python import Tkinter as tk import threading import signal import sys class MyTkApp(threading.Thread): def run(self): self.root = tk.Tk() self.root.mainloop() app = MyTkApp() app.start() def signal_handler(signal, frame): sys.stderr.write("Exiting...\n") # think only one of these is needed, not sure app.root.destroy() app.root.quit() signal.signal(signal.SIGINT, signal_handler) </code></pre> <p>Results:</p> <ul> <li>Run the app</li> <li>Ctrl-C in the terminal (nothing happens)</li> <li>Close the window</li> <li>"Exiting..." is printed and I get an error about the loop already having exited.</li> </ul> <p>What's going on here and how can I make Ctrl-C from the terminal close the app?</p> <hr> <p>Update: <a href="http://stackoverflow.com/a/13784297/7432">Adding a poll</a>, <a href="http://stackoverflow.com/questions/39840815/exiting-a-tkinter-app-with-ctrl-c-and-catching-sigint?noredirect=1#comment66972210_39840815">as suggested</a>, works in the main thread but does not help when started in another thread...</p> <pre><code>class MyTkApp(threading.Thread): def poll(self): sys.stderr.write("poll\n") self.root.after(50, self.poll) def run(self): self.root = tk.Tk() self.root.after(50, self.poll) self.root.mainloop() </code></pre>
0
2016-10-03T21:37:43Z
39,843,743
<p>Since your tkinter app is running in another thread, you do not need to set up the signal handler in the main thread and just use the following code block after the <code>app.start()</code> statement:</p> <pre><code>import time while app.is_alive(): try: time.sleep(0.5) except KeyboardInterrupt: app.root.destroy() break </code></pre> <p>You can then use <kbd>Ctrl-C</kbd> to raise the <code>KeyboardInterrupt</code> exception to close the tkinter app and break the while loop. The while loop will also be terminated if you close your tkinter app.</p> <p>Note that the above code is working only in Python 2 (as you use <code>Tkinter</code> in your code).</p>
1
2016-10-04T03:34:54Z
[ "python", "multithreading", "tkinter", "signals" ]
python generate a infinite list with certain condition
39,840,845
<p>I know there is generator yield in python like:</p> <pre><code>def f(n): x = n while True: yield x x = x+1 </code></pre> <p>So I try to convert this haskell function into python without using iterate: <a href="http://stackoverflow.com/questions/39809592/haskell-infinite-recursion-in-list-comprehension">Haskell infinite recursion in list comprehension</a></p> <p>I'm not sure how to define base case in python, also not sure how to combine if statement with this yield staff! here is what I try to do:</p> <pre><code>def orbit(x,y): while True: yield p (u,v) p (u,v) = (u^2 - v^2 + x, 2 * u * v + y) </code></pre>
2
2016-10-03T21:39:37Z
39,840,885
<p>I dont see where you're getting the <code>p</code> from. As far as I can see you can almost literally translate it from Haskell:</p> <pre><code>def orbit(x, y): u, v = 0, 0 while True: u, v = u**2 − v**2 + x, 2*u*v + y yield u, v </code></pre> <p>In their example, calling the function as <code>orbit(1, 2)</code>, <code>u</code> will be bound to <code>1</code> and <code>v</code> to <code>2</code> in the first round, then that (<code>(1, 2)</code>) is yielded. In the next iteration, <code>u = 1**2 - 2**2 + 1 = 1 - 4 + 1 = -2</code> and <code>v = 2*1*2 + 2 = 6</code>.</p>
3
2016-10-03T21:43:16Z
[ "python", "list", "python-3.x", "yield" ]
Using a global static variable server wide in Django
39,840,874
<p>I have a very long list of objects that I would like to only load from the db once to memory (Meaning not for each session) this list WILL change it's values and grow over time by user inputs, The reason I need it in memory is because I am doing some complex searches on it and want to give a quick answer back.</p> <p>My question is how do I load a list on the start of the server and keep it alive through sessions letting them all READ/WRITE to it.</p> <p>Will it be better to do a heavy SQL search instead of keeping the list alive through my server?</p>
1
2016-10-03T21:42:24Z
39,844,237
<p>The answer is that this is bad idea, you are opening a pandora's box specially since you need write access as well. However all is not lost. You can quite easily use <a href="https://redis-py.readthedocs.io/en/latest/" rel="nofollow">redis</a> for this task.</p> <p>Redis is a peristent data store but at the same time everything is held in memory. If the redis server runs on the same device as the web server access is almost instantaneous </p>
0
2016-10-04T04:36:27Z
[ "python", "django" ]
Cannot access sub-keys in OrderedDict
39,840,875
<p>I'm trying to define my ordinary dictionary as an OrderedDict, but I can't seem to access keys are the inner level.</p> <pre><code>my_dict = \ { 'key1': { 'subkey1':value1, 'subkey2':value2 } } my_ordered_dict = OrderedDict\ ([( 'key1', ( ('subkey1',value1), ('subkey2',value2) ) )]) </code></pre> <p>I can access <code>['key1']</code> for both cases, but I cannot access <code>['key1']['subkey1']</code> for the ordered dict.</p> <p>What am I doing wrong?</p>
0
2016-10-03T21:42:24Z
39,841,285
<p>The dictionary with 'subkey1' should also be defined as a OrderedDict ,if thats what you want. So it should be something like this</p> <pre><code>import collections my_ordered_dict = collections.OrderedDict() sub_dict=collections.OrderedDict() sub_dict['subkey1']=1 sub_dict['subkey2']=2 my_ordered_dict['key1']=sub_dict sub_dict=collections.OrderedDict() sub_dict['subkey1']=3 sub_dict['subkey2']=4 my_ordered_dict['key2']=sub_dict print my_ordered_dict['key1']['subkey1'] print my_ordered_dict['key2']['subkey1'] </code></pre> <p>The out put will be</p> <pre><code>1 3 </code></pre>
1
2016-10-03T22:18:35Z
[ "python", "ordereddictionary" ]
Cannot access sub-keys in OrderedDict
39,840,875
<p>I'm trying to define my ordinary dictionary as an OrderedDict, but I can't seem to access keys are the inner level.</p> <pre><code>my_dict = \ { 'key1': { 'subkey1':value1, 'subkey2':value2 } } my_ordered_dict = OrderedDict\ ([( 'key1', ( ('subkey1',value1), ('subkey2',value2) ) )]) </code></pre> <p>I can access <code>['key1']</code> for both cases, but I cannot access <code>['key1']['subkey1']</code> for the ordered dict.</p> <p>What am I doing wrong?</p>
0
2016-10-03T21:42:24Z
39,841,839
<p>If you want the inner level to also be an <code>OrderedDict</code> you need to explicitly define it as one. Since argument order matters when constructing <code>OrderedDict</code>s, in order to preserve it, you need to pass the keys and values as a sequence of <code>key, value</code> pairs as shown in the <a href="https://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes" rel="nofollow"><em><code>OrderedDict</code> Examples and Recipes</em></a> section of the documentation.</p> <p>Applying that to your example means you would need to do something like the following:</p> <pre><code>from collections import OrderedDict value1, value2 = 42, 69 my_ordered_dict = OrderedDict([ ('key1', OrderedDict([ ('subkey1', value1), ('subkey2', value2) ]) ) ]) print(my_ordered_dict['key1']['subkey1']) # --&gt; 42 </code></pre>
0
2016-10-03T23:14:01Z
[ "python", "ordereddictionary" ]
How does one control whitespace around a figure in matplotlib?(plt.tight_layout does not work)
39,840,882
<p>I have a matplotlib figure with 3 sub-plots. The consensus from stackexchange seems to be to use the plt.tight_layout in order to get rid of the whitespace around the figure. This does not solve the problem in my case.</p> <p>My code is as follows:</p> <pre><code>import numpy as np import os import pandas as pd import matplotlib as mpl from matplotlib import pyplot as plt my_dpi = 1500 plt.ion() index = np.linspace(0,5,10) combined = np.linspace(0,1,10) case1 = np.linspace(0,1,10) case2 = np.linspace(0,1,10) case3 = np.linspace(0,1,10) tsfont = {'fontname':'Times-Roman'} mpl.rcParams.update({'font.size': 18}) mpl.rc('font',family='Arial') ms = 0 f = plt.figure() f.set_size_inches(7.5,10) f.axison=False lw = 2 asp = 5 axarr1 = plt.subplot(3,1,1, adjustable='box',aspect = asp) axarr1.set_xlim(0,5,10) axarr1.set_ylim(0,1) axarr1.set_ylabel('y') axarr1.set_xlabel('$\\tau$', fontsize =25) p = axarr1.plot(index,combined,color='navy', linewidth=lw, label = "Healthy") axarr1.xaxis.set_label_coords(0.5, -0.05) ''' Duct 2 ''' axarr2 = plt.subplot(3,1,2, adjustable='box',aspect = asp) #axarr2.set_aspect('auto') axarr2.set_xlim(0,5,10) axarr2.set_ylim(0,1) axarr2.set_ylabel('y') axarr2.set_xlabel('$\\tau$', fontsize = 25) g = axarr2.plot(index,combined,color='navy', linewidth=lw) axarr2.xaxis.set_label_coords(0.5, -0.05) ''' Duct 3 ''' axarr3 = plt.subplot(3,1,3, adjustable='box',aspect = asp) axarr3.set_xlim(0,5,10) axarr3.set_ylim(0,1) axarr3.set_ylabel('y') axarr3.set_xlabel('$\\tau$', fontsize = 25) w = axarr3.plot(index,combined,color='navy', linewidth=lw) axarr3.xaxis.set_label_coords(0.5, -0.05) #plt.tight_layout() plt.show() </code></pre> <p>Without using plt.tight_layout() I get the following result</p> <p><a href="http://i.stack.imgur.com/WgVVo.png" rel="nofollow"><img src="http://i.stack.imgur.com/WgVVo.png" alt="enter image description here"></a></p> <p>Uncommenting the relevant line gives me</p> <p><a href="http://i.stack.imgur.com/SfOso.png" rel="nofollow"><img src="http://i.stack.imgur.com/SfOso.png" alt="As is obvious, while the vertical spacing changes, the horizontal spacing does not"></a></p> <p>As is obvious, while the vertical spacing changes, the horizontal spacing does not</p> <p>I'd like to know how to get rid of the horizontal whitespacing to the left and right.</p>
0
2016-10-03T21:43:07Z
39,840,932
<p>The <code>tight_layout</code> option places the images closer to the borders. However, in your case, there is nothing to fill this empty space with, so it doesn't work.</p> <p>If you want a narrower figure, you should change the horizontal dimension, e.g.:</p> <pre><code>plt.figure(..., tight_layout=True, figsize=(12, 5)) </code></pre> <p>This is in inches, experiment with the numbers until it looks good.</p> <p>You could also use 2 by 2 subplots to keep a square figure and use the space better:</p> <pre><code>plt.subplot(2, 2, ...) </code></pre> <p>although this may look suboptimal with a prime number of figures.</p>
0
2016-10-03T21:48:59Z
[ "python", "numpy", "matplotlib", "plot" ]
How to Use Lagged Time-Sereis Variables in a Python Pandas Regression Model?
39,840,890
<p>I'm creating time-series econometric regression models. The data is stored in a Pandas data frame.</p> <p><strong>How can I do lagged time-series econometric analysis using Python</strong>? I have used Eviews in the past (which is a standalone econometric program i.e. not a Python package). To estimate an ols equation using Eviews you can write something like:</p> <pre><code>equation eq1.ls log(usales) c log(usales(-1)) log(price(-1)) tv_spend radio_spend </code></pre> <p>Note the lagged dependent and lagged price terms. It's these lagged variables which seem to be difficult to handle using Python e.g. using scikit or statmodels (unless I've missed something).</p> <p>Once I've created a model I'd like to perform tests and use the model to forecast.</p> <p>I'm not interested in doing ARIMA, Exponential Smoothing, or Holt Winters time-series projections - I'm mainly interested in time-series OLS.</p>
0
2016-10-03T21:44:16Z
39,840,944
<p>pandas allows you to shift your data without moving the index such has</p> <pre><code>df.shift(-1) </code></pre> <p>will create a 1 index lag behing</p> <p>or</p> <pre><code>df.shift(1) </code></pre> <p>will create a forward lag of 1 index</p> <p>so if you have a daily time series, you could use df.shift(1) to create a 1 day lag in you values of price such has</p> <pre><code>df['lagprice'] = df['price'].shift(1) </code></pre> <p>after that if you want to do OLS you can look at scipy module here :</p> <p><a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.linregress.html" rel="nofollow">http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.linregress.html</a></p>
0
2016-10-03T21:49:54Z
[ "python", "pandas", "time-series", "regression" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub('[()]', '', fn) for ch in ['']: fn = fn.translate(ch, "_") return fn print(demicrosoft('Quercus stellata (26).jpg')) </code></pre>
0
2016-10-03T21:45:03Z
39,840,972
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> combined with a generator that iterates over the characters in your string while handling the logic for filtering out parentheses and replacing spaces with underscores:</p> <pre><code>PARENS = {'(', ')'} def demicrosoft(string): return ''.join('_' if c == ' ' else c for c in string if c not in PARENS) print(demicrosoft('Quercus stellata (26).jpg')) # Quercus_stellata_26.jpg </code></pre>
1
2016-10-03T21:51:42Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub('[()]', '', fn) for ch in ['']: fn = fn.translate(ch, "_") return fn print(demicrosoft('Quercus stellata (26).jpg')) </code></pre>
0
2016-10-03T21:45:03Z
39,841,009
<pre><code>import re def demicrosoft (fn): return '_'.join((''.join(re.split(r'[()]', fn)).split())) </code></pre>
1
2016-10-03T21:54:29Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub('[()]', '', fn) for ch in ['']: fn = fn.translate(ch, "_") return fn print(demicrosoft('Quercus stellata (26).jpg')) </code></pre>
0
2016-10-03T21:45:03Z
39,841,086
<p>From Zen of Python: Readability counts!</p> <pre><code>def demicrosoft (fn): dest = "" for char in fn: if char == ' ': dest += '_' elif char not in '()': dest += char return dest </code></pre>
0
2016-10-03T22:01:11Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub('[()]', '', fn) for ch in ['']: fn = fn.translate(ch, "_") return fn print(demicrosoft('Quercus stellata (26).jpg')) </code></pre>
0
2016-10-03T21:45:03Z
39,841,125
<pre><code>newString = re.sub("([\s\(\)])",lambda m:"_" if b.group(0) not in "()" else "",targetString) </code></pre> <p>im guessing its for a performance reasons and they want <code>O(N)</code> the generator expression should work ... here is an <code>re</code> solution</p>
0
2016-10-03T22:04:04Z
[ "python", "replace", "removeall" ]
Add variable of same index and add to list
39,840,995
<p>So I want to add a variable of the same index of another list and add that variable to a total. In this case I am trying to make the points be equal to the letters in a game of scrabble.</p> <p><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']</code> </p> <p><code>point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]</code></p> <p>So I would want <code>a</code> to equal to 1 and <code>c</code> to equal to 3. </p> <p>Say I have a <code>rack = ['c','a','t']</code><br> How could I make <code>'rack'</code> == <code>points = 5</code>?</p> <p>Here is my preexisting code: It gives a <code>Out[1]: 87</code> if I said <code>'c'</code> and for every single letter.</p> <pre><code>import random def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. """ # inFile: file inFile = open('words.txt', 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() return wordlist letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] bag_of_letters = [] for x in range(26): for i in range(letter_count[x]): bag_of_letters.append(letters[x]) rack = [] for i in range(7): rack.append(bag_of_letters.pop(random.randint(0,len(bag_of_letters)-1))) print (rack) points = 0 total_points = 0 round_count = 10 letterlst = [] while(round_count &gt;= 0): word = input("GIMME A LETTER TO COUNT THE SCORE OF: ") for i in word: letterlst += i for let in word: for letter in letters: for word_rack in rack: if let == word_rack: points += point_values[letters.index(letter)] total_points += points if round_count == 0: print("You have gotten",total_points,"points at the end of your round") print(points,"points this round") points = 0 round_count -= 1 </code></pre>
-3
2016-10-03T21:53:04Z
39,841,139
<p>Is this what you want?</p> <pre><code>wordlist = ['why', 'are', 'you', 'doing', 'this'] letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] score_list = [] for word in wordlist: score = 0 for letter in word: score += point_values[letters.index(letter)] score_list.append(score) print score_list </code></pre> <p>In your code, I can't find the definition of <code>letter_count</code> and why do you have to use <code>randint</code>?</p>
0
2016-10-03T22:05:28Z
[ "python", "indexing" ]
Add variable of same index and add to list
39,840,995
<p>So I want to add a variable of the same index of another list and add that variable to a total. In this case I am trying to make the points be equal to the letters in a game of scrabble.</p> <p><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']</code> </p> <p><code>point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]</code></p> <p>So I would want <code>a</code> to equal to 1 and <code>c</code> to equal to 3. </p> <p>Say I have a <code>rack = ['c','a','t']</code><br> How could I make <code>'rack'</code> == <code>points = 5</code>?</p> <p>Here is my preexisting code: It gives a <code>Out[1]: 87</code> if I said <code>'c'</code> and for every single letter.</p> <pre><code>import random def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. """ # inFile: file inFile = open('words.txt', 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() return wordlist letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] bag_of_letters = [] for x in range(26): for i in range(letter_count[x]): bag_of_letters.append(letters[x]) rack = [] for i in range(7): rack.append(bag_of_letters.pop(random.randint(0,len(bag_of_letters)-1))) print (rack) points = 0 total_points = 0 round_count = 10 letterlst = [] while(round_count &gt;= 0): word = input("GIMME A LETTER TO COUNT THE SCORE OF: ") for i in word: letterlst += i for let in word: for letter in letters: for word_rack in rack: if let == word_rack: points += point_values[letters.index(letter)] total_points += points if round_count == 0: print("You have gotten",total_points,"points at the end of your round") print(points,"points this round") points = 0 round_count -= 1 </code></pre>
-3
2016-10-03T21:53:04Z
39,841,521
<p>Below is the simplified version of your code:</p> <pre><code>&gt;&gt;&gt; letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] &gt;&gt;&gt; point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] &gt;&gt;&gt; my_string = 'cat' &gt;&gt;&gt; sum(point_values[letters.index(c)] for c in my_string) 5 </code></pre> <p><strong>Explanation</strong>: Iterate over each character in the string. Find the index of the char in <code>letters</code> list. Get the value of that index from <code>point_values</code>. Sum all the values. All this is been done in last line of code. Python is <em>MAGICAL</em>. Right? :)</p>
2
2016-10-03T22:40:04Z
[ "python", "indexing" ]
Escaping with backslash or quoting in the shell?
39,841,083
<p>When starting a program via the command line using <code>os.system(program file_argument))</code> and where the argument is a file (which might have whitespace in it) what is the best way to send the argument to the other program?</p> <p>I've looked at these options:</p> <ul> <li>Using <code>pipes.quote(file_name)</code> (or <code>shlex.quote(file_name)</code> for Python 3) which produces a string like this: <code>'/dir/file with white space'</code></li> <li>Using <code>re.escape(file_name)</code> which produces string like this: <code>/dir/file\ with\ white\ space</code></li> </ul> <p>Are there differences between using these that might impact the program that is called? (Are there any other options?) Anything else i need to consider?</p>
0
2016-10-03T22:00:49Z
39,843,906
<pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.call(['cat', 'file with space.txt']) </code></pre> <p>Using <code>os.system</code>, while simple to get started, breaks down when trying to do more complicated tasks.</p> <p>I wish I had given up on <code>os.system</code> much earlier and just got familiar with <code>subprocess</code>. Well worth the time.</p>
2
2016-10-04T03:54:46Z
[ "python", "shell" ]
Under what circumstances must I use py-files option of spark-submit?
39,841,084
<p>Just poking around spark-submit, I was under the impression that if my application has got dependencies on other .py files then I have to distribute them using the py-files option (see <a href="http://spark.apache.org/docs/latest/submitting-applications.html#bundling-your-applications-dependencies" rel="nofollow">bundling your applications dependencies</a>). I took that to mean any file had to be declared using py-files yet the following works fine... two <code>.py</code> files: </p> <p><code>spark_submit_test_lib.py</code>:</p> <pre><code>def do_sum(sc) : data = [1, 2, 3, 4, 5] distData = sc.parallelize(data) return distData.sum() </code></pre> <p>and <code>spark_submit_test.py</code>: </p> <pre><code>from pyspark import SparkContext, SparkConf from spark_submit_test_lib import do_sum conf = SparkConf().setAppName('JT_test') sc = SparkContext(conf=conf) print do_sum(sc) </code></pre> <p>submitted using: </p> <pre><code>spark-submit --queue 'myqueue' spark_submit_test.py </code></pre> <p>All worked fine. Code ran, yields the correct result, spark-submit terminates gracefully.<br> However, I would have thought having read the documentation that I would have had to do this: </p> <pre><code>spark-submit --queue 'myqueue' --py-files spark_submit_test_lib.py spark_submit_test.py </code></pre> <p>That still worked of course. I'm just wondering why the former worked as well. Any suggestions?</p>
0
2016-10-03T22:00:58Z
39,841,219
<p>You must be submitting this in local environment where your driver and executors runs on the same machine , that is the the reason it worked ,but if you deploy in cluster and try to run from there you have to use --pf-files option.</p> <p>Please check the <a href="http://spark.apache.org/docs/latest/#running-the-examples-and-shell" rel="nofollow">link</a> for more details</p>
1
2016-10-03T22:11:35Z
[ "python", "apache-spark" ]
Parsing floating number from ping output in text file
39,841,200
<p>So I am writing this python program that must extract the round trip time from a text file that contains numerous pings, whats in the text file I previewed below:</p> <pre><code> 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=12.6ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=1864ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=107.8ms </code></pre> <p>What I want to extract from the text file is the 12.6, 1864, and the 107.8. I used regex to do this and have the following:</p> <pre><code> import re ping = open("pingoutput.txt") rawping = ping.read() roundtriptimes = re.findall(r'times=(\d+.\d+)', rawping) roundtriptimes.sort() print (roundtriptimes) </code></pre> <p>The issue I'm having is that I believe the numbers are being read into the roundtriptimes list as strings so when I go to sort them they do not sort as I would like them to. </p> <p>Any idea how to modify my regex findall command to make sure it recognizes them as numbers would help tremendously! Thanks!</p>
-3
2016-10-03T22:09:59Z
39,841,279
<p>I don't know of a way to do that in RegEx, but if you add the following line before the sort, it should take care of it for you:</p> <pre><code>roundtriptimes[:] = [float(x) for x in roundtriptimes] </code></pre>
1
2016-10-03T22:18:19Z
[ "python", "regex", "ping", "text-parsing" ]
Parsing floating number from ping output in text file
39,841,200
<p>So I am writing this python program that must extract the round trip time from a text file that contains numerous pings, whats in the text file I previewed below:</p> <pre><code> 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=12.6ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=1864ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=107.8ms </code></pre> <p>What I want to extract from the text file is the 12.6, 1864, and the 107.8. I used regex to do this and have the following:</p> <pre><code> import re ping = open("pingoutput.txt") rawping = ping.read() roundtriptimes = re.findall(r'times=(\d+.\d+)', rawping) roundtriptimes.sort() print (roundtriptimes) </code></pre> <p>The issue I'm having is that I believe the numbers are being read into the roundtriptimes list as strings so when I go to sort them they do not sort as I would like them to. </p> <p>Any idea how to modify my regex findall command to make sure it recognizes them as numbers would help tremendously! Thanks!</p>
-3
2016-10-03T22:09:59Z
39,841,298
<h1>Non-regex:</h1> <p>Simply performing splits on space, grabbing the last entry, then split on <code>=</code>, grab the second part of the list and omit the last two components (ms). Cast to a float. </p> <p>All of that is done in a list-comprehension:</p> <p>Note that <code>readlines</code> is used to have a list containing each line of the file, which will be much easier to manage.</p> <pre><code>with open('ping_results.txt') as f: data = f.readlines() times = [float(line.split()[-1].split('=')[1][:-2]) for line in data] print(times) # [12.6, 1864.0, 107.8] </code></pre> <h1>regex:</h1> <p>The key thing here is to pay attention to the regex being used: </p> <pre><code>time=(\d*\.?\d+) </code></pre> <p>Look for <code>time=</code>, then start a capture group <code>()</code>, and grab digits (<code>\d*</code>), optional decimal (<code>\.?</code>), digits (<code>\d+</code>).</p> <pre><code>import re with open('ping_results.txt') as f: data = f.readlines() times = [float(re.findall('time=(\d*\.?\d+)', line)[0]) for line in data] print(times) # [12.6, 1864.0, 107.8] </code></pre>
1
2016-10-03T22:20:15Z
[ "python", "regex", "ping", "text-parsing" ]
How to "melt" `pandas.DataFrame` objects? (Python 3)
39,841,204
<p>I'm trying to <code>melt</code> certain columns of a <code>pd.DataFrame</code> while preserving columns of the other. In this case, I want to <code>melt</code> <code>sine</code> and <code>cosine</code> columns into <code>values</code> and then which column they came from (i.e. <code>sine</code> or <code>cosine</code>) into a new columns entitled <code>data_type</code> then preserving the original <code>desc</code> column.</p> <p><strong>How can I use <code>pd.melt</code> to achieve this w/o melting and concatenating each component manually?</strong> </p> <pre><code># Data a = np.linspace(0,2*np.pi,100) DF_data = pd.DataFrame([a, np.sin(np.pi*a), np.cos(np.pi*a)], index=["t", "sine", "cosine"], columns=["t_%d"%_ for _ in range(100)]).T DF_data["desc"] = ["info about this" for _ in DF_data.index] </code></pre> <p><a href="http://i.stack.imgur.com/cDNbN.png" rel="nofollow"><img src="http://i.stack.imgur.com/cDNbN.png" alt="enter image description here"></a></p> <p>The round about way I did it:</p> <pre><code># Melt each part DF_melt_A = pd.DataFrame([DF_data["t"], DF_data["sine"], pd.Series(DF_data.shape[0]*["sine"], index=DF_data.index, name="data_type"), DF_data["desc"]]).T.reset_index() DF_melt_A.columns = ["idx","t","values","data_type","desc"] DF_melt_B = pd.DataFrame([DF_data["t"], DF_data["cosine"], pd.Series(DF_data.shape[0]*["cosine"], index=DF_data.index, name="data_type"), DF_data["desc"]]).T.reset_index() DF_melt_B.columns = ["idx","t","values","data_type","desc"] # Merge pd.concat([DF_melt_A, DF_melt_B], axis=0, ignore_index=True) </code></pre> <p><a href="http://i.stack.imgur.com/JJbep.png" rel="nofollow"><img src="http://i.stack.imgur.com/JJbep.png" alt="enter image description here"></a></p> <p>If I do <code>pd.melt(DF_data</code> I get a complete meltdown</p> <p><a href="http://i.stack.imgur.com/l5rEY.png" rel="nofollow"><img src="http://i.stack.imgur.com/l5rEY.png" alt="enter image description here"></a></p> <p>In response to the comments: <a href="http://i.stack.imgur.com/y1YCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/y1YCp.png" alt="enter image description here"></a></p>
2
2016-10-03T22:10:08Z
39,842,057
<p>allright so I had to create a similar df because I did not have access to your <code>a</code> variable. I change your <code>a</code> variable for a list from 0 to 99... so t will be 0 to 99</p> <p>you could do this :</p> <pre><code>a = range(0, 100) DF_data = pd.DataFrame([a, [np.sin(x)for x in a], [np.cos(x)for x in a]], index=["t", "sine", "cosine"], columns=["t_%d"%_ for _ in range(100)]).T DF_data["desc"] = ["info about this" for _ in DF_data.index] df = pd.melt(DF_data, id_vars=['t','desc']) df.head(5) </code></pre> <p>this should return what you are looking for.</p> <pre><code> t desc variable value 0 0.0 info about this sine 0.000000 1 1.0 info about this sine 0.841471 2 2.0 info about this sine 0.909297 3 3.0 info about this sine 0.141120 4 4.0 info about this sine -0.756802 </code></pre>
1
2016-10-03T23:38:43Z
[ "python", "pandas", "matrix", "dataframe", "melt" ]
django 1.10 render template html class
39,841,233
<p>After a user fills out a form on my site, I user render(request, html, context). I'd like to return the user to the same part of the page after they register. I am not using any front end frameworks (like angular - thats my next project). How would I go about doing this?</p> <p>views.py:</p> <pre><code>def homepage(request): countries = Country.objects.count() cities = City.objects.count() start_trip_date = date(xxxx, x, x) today = date.today() total_days = today - start_trip_date queryset_list = Post.objects.active()[:6] query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query) | Q(content__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ).distinct() contact_form = EmailUpdatesForm(request.POST or None) if contact_form.is_valid(): contact = contact_form.save(commit=False) contact.email = request.POST['email'] contact.first_name = request.POST['first_name'] contact.save() profile_data = { 'email': contact.email, 'first_name': contact.first_name, } plaintext = get_template('email/frontpage_registered_email/email_text.txt') htmly = get_template('email/frontpage_registered_email/email_template.html') text_content = plaintext.render(profile_data) html_content = htmly.render(profile_data) subject = "{0}, thank you for registering with xx!".format(contact.first_name) from_email = 'xx@gmail.com' to_email = contact.email msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request, "homepage/homepage.html", {}) else: print contact_form.errors, context = { 'object_list': queryset_list, 'countries': countries, 'cities': cities, 'days_traveling': total_days.days, 'contact_form': contact_form, } return render(request, "homepage/homepage.html", context) </code></pre> <p>and a made up html to show what I mean:</p> <pre><code>&lt;body&gt; &lt;div class="first"&gt;content&lt;/div&gt; &lt;div class="second"&gt; &lt;form id="contact_form" method="POST" action="." enctype="multipart/form-data" novalidate&gt; &lt;fieldset&gt; {% csrf_toke %} {{ contact_form|crispy }} &lt;input class="btn..." type="submit" name="submit" value="Register" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>In the above I want to return the user to the div class="second".</p> <p>Thanks you.</p>
0
2016-10-03T22:13:26Z
39,841,808
<p>To do this, you need to differentiate the default GET request to access the page and the POST of the form. </p> <p>E.g. You could do:</p> <pre><code>contact_form = EmailUpdatesForm() if request.method == 'POST': contact_form = EmailUpdatesForm(request.POST) if contact_form.is_valid(): contact = contact_form.save(commit=False) contact.email = request.POST['email'] .... .... form_submit = True </code></pre> <p>and pass form_submit in the context. </p> <p>Then, in HTML:</p> <pre><code>{% if form_submit %} &lt;div class="second"&gt;&lt;/div&gt; {% else %} &lt;div class="first"&gt;&lt;/div&gt; {% endif %} </code></pre>
0
2016-10-03T23:10:44Z
[ "python", "django", "django-templates", "django-email" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in range (len(List)): if List[i] &gt;= 0: product *= i List.append(xs[i]) return xs </code></pre>
-4
2016-10-03T22:17:17Z
39,841,322
<p>You're iterating over an empty list, and that loop would be trying to access elements that don't exist, change the <code>product</code>, and append unchanged elements from the original list to the new list. And then you return the original, unchanged list anyway. Basically, almost every line in your code is wrong.</p> <p>You should be looping over the input list and appending multiplied elements to the new list, then return the new list:</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in xs: if i &gt; 0: List.append(i*product) return List </code></pre> <p>Also, 0 is not a positive number. Use <code>&gt;</code> instead of <code>&gt;=</code>.</p>
0
2016-10-03T22:22:29Z
[ "python", "list", "numbers", "multiplying" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in range (len(List)): if List[i] &gt;= 0: product *= i List.append(xs[i]) return xs </code></pre>
-4
2016-10-03T22:17:17Z
39,841,359
<p>Modifying your function it should be something like this. 0 is not a positive number.So using > instead of >=.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in xs: if i &gt; 0: i=i*product List.append(i) return List </code></pre> <p>But this can be done like this also</p> <pre><code>def triple_positives(xs): return [3*i if i&gt;0 else i for i in xs ] </code></pre>
0
2016-10-03T22:25:20Z
[ "python", "list", "numbers", "multiplying" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in range (len(List)): if List[i] &gt;= 0: product *= i List.append(xs[i]) return xs </code></pre>
-4
2016-10-03T22:17:17Z
39,841,377
<p>In your code, there are multiple issues. Below is the updated version of it with fixes:</p> <pre><code>&gt;&gt;&gt; def triple_positives(xs): ... List = [] ... product = 3 ... for i in range (len(xs)): ... if xs[i] &gt;= 0: ... List.append(xs[i]*3) ... else: ... List.append(xs[i]) ... return List ... &gt;&gt;&gt; my_list = [1, 2, -1, 5, -2] &gt;&gt;&gt; triple_positives(my_list) [3, 6, -1, 15, -2] </code></pre> <p>Alternatively, you may achieve this using List Comprehension as:</p> <pre><code>&gt;&gt;&gt; [item * 3 if item &gt; 0 else item for item in my_list] [3, 6, -1, 15, -2] </code></pre>
0
2016-10-03T22:27:33Z
[ "python", "list", "numbers", "multiplying" ]
Why might this link not be working...?
39,841,276
<p>I'm rendering a bunch of posts on a page where a user can browse listings and click on one of them and be sent to a 'singles page' for more information on whatever product they clicked. This method works for every link EXCEPT for the first one. </p> <p>Anytime I click on the very first link of the page, I get a <strong>Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</strong> error.</p> <p>The logic I have in place for the HMTL/jinja is (everything is closed off properly, I'm cutting some unnecessary code for the sake of brevity):</p> <pre><code>{% set i = 0 %} {% for row in data %} {% set i = i + 1 %} &lt;a href="/iLike/{{ i }}"&gt; &lt;li&gt;content&lt;/li&gt; &lt;/a&gt; </code></pre> <p>and my python code:</p> <pre><code>@app.route('/iLike/&lt;int:num&gt;', methods=['GET','POST']) def single2(num): try: loc = session.get('loc') transType = session.get('transType') data = singlesQuery() return render_template('single.html', loc=loc,transType=transType,data=data[num-1]) except Exception as e: return (str(e)) </code></pre>
-1
2016-10-03T22:17:46Z
39,841,485
<p>There is no need to build URLs manually. The best way it to use flask's built-in function <a href="http://flask.pocoo.org/docs/0.11/api/#flask.url_for" rel="nofollow"><code>url_for</code></a>:</p> <pre><code>{{url_for('single2', num=i)}} </code></pre> <p>There is also no need for calculating the <code>i</code> manually, becaue there is built-in <code>loop.index</code> and <code>loop.index0</code>:</p> <pre><code>{% for row in data %} &lt;a href="{{url_for('single2', num=loop.index)}}"&gt; </code></pre> <p>I believe this should always create a valid URL.</p>
2
2016-10-03T22:37:42Z
[ "python", "flask", "jinja2" ]
How to Count Number of Data Points?
39,841,333
<p>I have 200 data points scattered from this loop:</p> <pre><code>import math plt.figure() for i in range(200): r=random.uniform(-1,1) x=random.uniform(-1,1) if math.sqrt(x**2+r**2)&lt;1: plt.plot(x,r,'r.') else: plt.plot(x,r,'k.') redraw() </code></pre> <p>So there will be a number of plots that meets the <code>if</code> condition. I want to know the number of those points. What should I do?</p>
0
2016-10-03T22:23:13Z
39,841,445
<p>You would just need to increment a counter when the condition is met:</p> <pre><code>import math plt.figure() good_samples = 0 for i in range(200): r=random.uniform(-1,1) x=random.uniform(-1,1) if math.sqrt(x**2+r**2)&lt;1: plt.plot(x,r,'r.') good_samples += 1 else: plt.plot(x,r,'k.') redraw() print "Counted {} good samples".format(good_samples) </code></pre>
3
2016-10-03T22:33:06Z
[ "python", "python-2.7" ]
How to fix python program that appears to be doing an extra loop?
39,841,451
<p>A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... if not I can try to explain better. Perhaps the code will help)</p> <pre><code>def getInput(emptyList): inputString = input("Please enter a sentence:\n").strip().upper() functionList = [x for x in inputString] emptyList.extend(functionList) return 0 def sortList(listA,listB): listA.sort() currentElement = listA[0] compareTo = listA[0] elementsCounted = 0 i = 0 listB.append([]) while elementsCounted &lt; len(listA): while currentElement == compareTo: listB[i].append(currentElement) elementsCounted += 1 print(listB) if elementsCounted &lt; len(listA): currentElement = listA[elementsCounted] else: break if currentElement != compareTo: i += 1 listB.append([]) compareTo = listA[i] return 0 def main(): myList = list() sortedList = list() getInput(myList) sortList(myList,sortedList) print(sortedList) main() </code></pre> <p>If the user enters <code>qwerty</code>, the program returns <code>[['E'], ['Q'], ['R'], ['T'], ['W'], ['Y']]</code> which is correct but if the user enters <code>qwwerrty</code> the program returns <code>[['E'], ['Q'], ['R', 'R'], [], ['T'], ['W', 'W'], [], ['Y']]</code>. Note the extra empty list after each "double" character. It appears that the loop is making one extra iteration or that the <code>if</code> statement before <code>listB.append([])</code> isn't written properly.</p> <p>I can't seem to figure it out more than this. Thank you in advance for your help.</p> <p>NOTE: <code>elementsCounted</code> should be a cumulative tally of each element that has been processed from listA. <code>i</code> is the index of the current element in listB. For example, if <code>['A','A','B']</code> was listA and the program is processing the second A, then it is the second element being counted but <code>i</code> is still 0 because it belongs in listB[0]. <code>currentElement</code> is the one currently being processed and it is being compared to the first element that was processed as that "i". For the <code>['A','A','B'] example, when processing the second A, it is being compared to the first A to see if</code>i<code>should be incremented. In the next loop, it is comparing 'B' to the first 'A' and thus will increase</code>i` by one since 'B' belongs in the next sub-list.</p>
0
2016-10-03T22:33:57Z
39,841,663
<p>Your mistake lies in this part:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[i] </code></pre> <p>It should be:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[elementsCounted] </code></pre> <p>It's an overly complex function for such a simple task.</p>
1
2016-10-03T22:53:28Z
[ "python", "list", "loops", "if-statement", "while-loop" ]
How to fix python program that appears to be doing an extra loop?
39,841,451
<p>A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... if not I can try to explain better. Perhaps the code will help)</p> <pre><code>def getInput(emptyList): inputString = input("Please enter a sentence:\n").strip().upper() functionList = [x for x in inputString] emptyList.extend(functionList) return 0 def sortList(listA,listB): listA.sort() currentElement = listA[0] compareTo = listA[0] elementsCounted = 0 i = 0 listB.append([]) while elementsCounted &lt; len(listA): while currentElement == compareTo: listB[i].append(currentElement) elementsCounted += 1 print(listB) if elementsCounted &lt; len(listA): currentElement = listA[elementsCounted] else: break if currentElement != compareTo: i += 1 listB.append([]) compareTo = listA[i] return 0 def main(): myList = list() sortedList = list() getInput(myList) sortList(myList,sortedList) print(sortedList) main() </code></pre> <p>If the user enters <code>qwerty</code>, the program returns <code>[['E'], ['Q'], ['R'], ['T'], ['W'], ['Y']]</code> which is correct but if the user enters <code>qwwerrty</code> the program returns <code>[['E'], ['Q'], ['R', 'R'], [], ['T'], ['W', 'W'], [], ['Y']]</code>. Note the extra empty list after each "double" character. It appears that the loop is making one extra iteration or that the <code>if</code> statement before <code>listB.append([])</code> isn't written properly.</p> <p>I can't seem to figure it out more than this. Thank you in advance for your help.</p> <p>NOTE: <code>elementsCounted</code> should be a cumulative tally of each element that has been processed from listA. <code>i</code> is the index of the current element in listB. For example, if <code>['A','A','B']</code> was listA and the program is processing the second A, then it is the second element being counted but <code>i</code> is still 0 because it belongs in listB[0]. <code>currentElement</code> is the one currently being processed and it is being compared to the first element that was processed as that "i". For the <code>['A','A','B'] example, when processing the second A, it is being compared to the first A to see if</code>i<code>should be incremented. In the next loop, it is comparing 'B' to the first 'A' and thus will increase</code>i` by one since 'B' belongs in the next sub-list.</p>
0
2016-10-03T22:33:57Z
39,841,744
<p>If you want a simpler approach:</p> <pre><code>&gt;&gt;&gt; def make_lists(inp): ... i = 0 ... indices = {} ... result = [] ... for c in sorted(inp): ... if c not in indices: ... result.append([c]) ... indices[c] = i ... i += 1 ... else: ... result[indices[c]].append(c) ... return result ... &gt;&gt;&gt; make_lists("qwerty") [['e'], ['q'], ['r'], ['t'], ['w'], ['y']] &gt;&gt;&gt; make_lists("qwwerrty") [['e'], ['q'], ['r', 'r'], ['t'], ['w', 'w'], ['y']] &gt;&gt;&gt; </code></pre> <p>Or if you want a one-liner:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; [list(g) for _,g in itertools.groupby(sorted('qwwerrty'))] [['e'], ['q'], ['r', 'r'], ['t'], ['w', 'w'], ['y']] &gt;&gt;&gt; </code></pre>
1
2016-10-03T23:04:35Z
[ "python", "list", "loops", "if-statement", "while-loop" ]
cannot import name multiarray Django Apache2
39,841,540
<p>I am currently running a django app on an ec2 with apache. The app works fine when I run it using djangos runserver command. However I receive a 'cannot import name multiarray' when I run it using apache. I have tried reinstalling numpy and various packages many times and have still not had any luck. Below is my .conf file for apache. I am using python3.4 and have recently updated pip within my venv. I can provide more information if necessary. </p> <pre><code> Include conf-available/serve-cgi-bin.conf WSGISCRIPTALIAS /site /home/ubuntu/site/initsite/wsgi.py WSGIDaemonProcess site_group threads=15 display-name=%{GROUP} python-path='/home/ubuntu/site:/home/ubuntu/site/envsite/lib/python3.4/site-packages' &lt;Directory /home/ubuntu/site&gt; &lt;files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; &lt;Location /site&gt; WSGIProcessGroup site_group &lt;/Location&gt; Alias /site1/ /home/ubuntu/site/fullsite/static/css &lt;Directory /home/ubuntu/site/fullsite/static/css&gt; Require all granted AllowOverride All &lt;/Directory&gt; </code></pre> <p>Traceback:</p> <pre><code>File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/urls/resolvers.py" in resolve 270. for pattern in self.url_patterns: File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/urls/resolvers.py" in url_patterns 313. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/urls/resolvers.py" in urlconf_module 306. return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/home/ubuntu/site/initSite/urls.py" in &lt;module&gt; 21. url(r'', include('fullSite.urls')), File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/django/conf/urls/__init__.py" in include 50. urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/home/ubuntu/site/fullSite/urls.py" in &lt;module&gt; 2. from . import views File "/home/ubuntu/site/fullSite/views.py" in &lt;module&gt; 1. import numpy as np File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/numpy/__init__.py" in &lt;module&gt; 180. from . import add_newdocs File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/numpy/add_newdocs.py" in &lt;module&gt; 13. from numpy.lib import add_newdoc File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/numpy/lib/__init__.py" in &lt;module&gt; 8. from .type_check import * File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/numpy/lib/type_check.py" in &lt;module&gt; 11. import numpy.core.numeric as _nx File "/home/ubuntu/site/envsite/lib/python3.4/site-packages/numpy/core/__init__.py" in &lt;module&gt; 14. from . import multiarray Exception Type: ImportError at / Exception Value: cannot import name multiarray </code></pre> <p>drwxrwxr-x 5 ubuntu ubuntu 4096 Oct 3 22:31 site</p>
0
2016-10-03T22:41:17Z
39,885,673
<p>I can possibly spot three issues that may effect your setup.</p> <p>Your virutalenv is placed inside your project itself, this in my experience sometimes leads to conflicts. Virtualenvs and the project should always be separated. May I suggest a structures such as:</p> <p>/home/ubuntu/site - django project files /home/ubuntu/virtualenv/ - for the virtualenv</p> <p>The second issue is that you have placed the site and the virtualenv inside a user's home directly. Though you have set the top level directory permissions correctly, it may still be very likely that sub folders, files inside <code>/home/ubuntu/site</code> or <code>/home/ubuntu/virtualenv/</code> may be inaccessible to the apache user. This is very likely to happen if you made additions changes after the initial permissions were set.</p> <p>The third issue is that you may have a corrupted numpy installation, please uninstall and install again and make sure to use pip3 instead of pip. To be more specific: <code>pip3 install numpy</code></p>
0
2016-10-06T00:25:26Z
[ "python", "django", "apache", "numpy", "python-3.4" ]
matplotlib histogram: how to display the count over the bar?
39,841,733
<p>With matplotlib's <code>hist</code> function, how can one make it display the count for each bin over the bar?</p> <p>For example,</p> <pre><code>import matplotlib.pyplot as plt data = [ ... ] # some data plt.hist(data, bins=10) </code></pre> <p>How can we make the count in each bin display over its bar?</p>
0
2016-10-03T23:02:09Z
39,842,288
<p>it seems <code>hist</code> can't do this,you can write some like :</p> <pre><code>your_bins=20 data=[] arr=plt.hist(data,bins=your_bins) for i in range(your_bins): plt.text(arr[1][i],arr[0][i],str(arr[0][i])) </code></pre>
1
2016-10-04T00:06:55Z
[ "python", "matplotlib" ]
Values Within range of if statement not printing (Runge-Kutta Fourth Order in Python)
39,841,772
<p>I am writing a code to perform a Fourth Order Runge-Kutta numerical approximation with adaptive step size. </p> <pre><code>def f(x, t): #integrating function return -x def exact(t): #exact solution return np.exp(-t) def Rk4(x0, t0, dt): #Runge-Kutta Fourth Order t = np.arange(0, 1+dt, dt) n = len(t) x = np.array([x0]*n) x[0],t[0] = x0,t0 for i in range(n-1): h = t[i+1]-t[i] k1 = h*f(x[i], t[i]) k2 = h*f(x[i] + c21*k1, t[i] + c20*h) k3 = h*f(x[i] + c31*k1 + c32*k2, t[i] + c30*h) k4 = h*f(x[i] + c41*k1 + c42*k2 + c43*k3, t[i] + c40*h) k5 = h*f(x[i] + c51*k1 + c52*k2 + c53*k3 + c54*k4, t[i] + c50*h) k6 = h*f(x[i] + c61*k1 + c62*k2 + c63*k3 + c64*k4 + c65*k5, t[i] + c60*h) x[i+1] = x[i] + a1*k1 + a3*k3 + a4*k4 + a5*k5 x5 = x[i] + b1*k1 + b3*k3 + b4*k4 + b5*k5 + b6*k6 E = abs(x[n-1]-exact(t[n-1])) #error print(E) if E &lt; 10^-5: #error tolerance return x[n-1] #approximation print("For dt = 10e-2, x(1) =",Rk4(1.0,0.0,10e-2)) print("For dt = 10e-3, x(1) =",Rk4(1.0,0.0,10e-3)) </code></pre> <p>However, when I run the code, it prints:</p> <pre><code>5.76914409023e-08 For dt = 10e-2, x(1) = None 4.8151482801e-12 For dt = 10e-3, x(1) = None </code></pre> <p>Therefore the error, E, is less than 10^-5 in both cases, yet it doesn't print x(1).</p>
1
2016-10-03T23:07:13Z
39,841,813
<p><code>^</code> is <a href="https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations" rel="nofollow">bitwise exclusive or</a> in Python, not exponentiation; that's <code>**</code>. So <code>10^-5</code> (10 xor -5) is -15, and none of your errors is less than -15.</p> <p>You probably want the scientific notation constant <code>1e-5</code> or, if you want to write it as an actual exponentiation operation, <code>10 ** -5</code>.</p> <p>For those concerned with performance: the expression using <code>**</code> is actually compiled to a constant when Python loads the script, since the arguments are both constants, so it won't have any performance impact to write it that way. :-)</p>
3
2016-10-03T23:11:41Z
[ "python", "if-statement", "runge-kutta" ]
I'm writing the follow python script as a way to implement a slot machine type game using random numbers
39,841,804
<pre><code>from getch import getch, pause from random import randint def wheel_spin(): tokens = 100 while tokens &gt; 0: num_input= getch() if num_input == ' ': print "You Hit Space Bar" draw1 = randint(1,6) draw2 = randint(1,6) draw3 = randint(1,6) print draw1 , draw2 ,draw3 winning(draw1,draw2,draw3) tokens -= 1 #pause() def winning(draw1,draw2,draw3): if draw1 == draw2 or draw2 == draw3: print "YOU WIN" tokens += 10 else: pass wheel_spin() </code></pre> <p>The code works fine and generates random numbers but when it comes to the "winning" function where it is supposed to reward the player for getting two of the same numbers it doesn't work I get the following error </p> <blockquote> <p>YOU WIN Traceback (most recent call last): File "Exercise 36 Designing and Debugging.py", line 59, in wheel_spin() File "Exercise 36 Designing and Debugging.py", line 31, in wheel_spin winning(draw1,draw2,draw3) File "Exercise 36 Designing and Debugging.py", line 51, in winning tokens += 10 UnboundLocalError: local variable 'tokens' referenced before assignment</p> </blockquote> <p>Any help will be greatly appreciated </p>
0
2016-10-03T23:10:17Z
39,841,820
<p><code>tokens</code> is undefined in the <code>winning</code> method. It's declared in the <code>spin_wheel</code> and is scope-limited to only that method. You either want to pass it in or make it global.</p> <pre><code>tokens = 10 def spin_wheel(): global tokens ... def winning(): global tokens ... </code></pre>
0
2016-10-03T23:12:09Z
[ "python", "function" ]
If Statement Syntax in Python
39,841,887
<p>I get an error with the below code on the line that says, <code>if (str(listGroup) == "FTPDST"):</code>. I'm pretty sure my if, elif, else statement is correct syntax. Please let me know if my syntax is wrong on that line or anywhere else I get errors because the below code won't run, and it throws an <code>SyntaxError: invalid syntax</code> for the line, <code>if (str(listGroup) == "FTPDST")</code>. My list have been initialized in my code. I'm just not showing it below. Thanks.</p> <pre><code>def parseConfigForIso(searchString, listGroup): fi = open(panConfig,"r") for line in fi: if searchString in line: lineList=line.split() for item in listList: m = re.search(r'(\d{1,3}.){3}\d{1,3}(-\d{2}|slash\d{2})?',item, re.M|re.I) if m: if (str(listGroup) == "FTPDST"): ftpDstList.append(str(m.group(0)) elif (str(listGroup) == "FTPSRC"): ftpSrcList.append(str(m.group(0)) elif (str(listGroup) == "SSHDST"): sshDstList.append(str(m.group(0)) elif (str(listGroup) == "APPID"): appIdList.append(str(m.group(0)) else: print "you inputted an incorrect group as a parameter into the parseConfigForIso function" fi.close() parseConfigForIso('search string', "FTPSRC") </code></pre>
0
2016-10-03T23:19:38Z
39,841,920
<p>You're missing a <code>)</code> in all <code>.append(str(m.group(0))</code>.</p>
4
2016-10-03T23:24:23Z
[ "python", "if-statement" ]
Separate joined words in a string using python
39,841,918
<pre><code>"10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goods referred to HGI QLD for further action.Attachments:Nil34FEB2004" </code></pre> <p>What I want to do is to read this string in python and separate the joined words. What I exactly want is a regular expression to separate the joined words in the string. </p> <p>I want to read the above string from a file and the output should be as follows:</p> <pre><code>"10 JAN 2015 AirMail standard envelope from Hyderabad Address details : John Cena Palm Drive Adelaide. Also calculated: Nil Action Taken: Goods referred to USG for further action. Attachments : Nil 60 FEB 2004." </code></pre> <p>(Separate the joined words)</p> <p>I need to write a regular expression to separate:</p> <p><code>'10Jan2015AirMail', 'HyderabadAddress', 'details:John', 'DriveAdelaide'</code></p> <p>Need a regular expression to identify joined words like above and separate them with a space in the same string like </p> <p>'10 Jan 2015 AirMail, 'Hyderabad Address', 'details : John'</p> <p>text = open('C:\sample.txt', 'r').read().replace("\n","").replace("\t","").replace("-",""‌​).replace("/"," ") </p> <p>newtext = re.sub('[a-zA-Z0-9_:]','',text) #This regex does not work.Please assist</p> <p>print text print newtext</p> <p>The above code does not work</p>
-1
2016-10-03T23:23:52Z
39,842,705
<p>I know that this solution can be done pretty much simpler classifying chars in sets (upper, lower, numeric) but I preferred to do a much more verbose solution:</p> <pre><code>test_text = "10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goods referred to HGI QLD for further action.Attachments:Nil34FEB2004" splitted_text = test_text.split(' ') num = False low = False upp = False result = [] for word in ss: new_word = '' if not word.isupper() and not word.islower(): if word[0].isnumeric(): num = True low = False upp = False elif word[0].islower(): num = False low = True upp = False elif word[0].isupper(): num = False low = False upp = True for letter in word: if letter.isnumeric(): if num: new_word += letter else: new_word += ' ' + letter low = False upp = False num = True elif letter.islower(): if low or upp: new_word += letter else: new_word += ' ' + letter low = True upp = False num = False elif letter.isupper(): if low or num: new_word += ' ' + letter else: new_word += letter low = False upp = True num = False else: new_word += ' ' + letter result.append(''.join(new_word)) else: result.append(word) ' '.join(result) #'10 JAN 2015 Air Mail standard envelope from Hyderabad Address details : John Cena Palm Drive Adelaide . Also Contained : Nil Action Taken : Goods referred to HGI QLD for further action . Attachments : Nil 34 FEB 2004' </code></pre> <p>Sometimes one just need to be pointed int he right direction.</p>
0
2016-10-04T01:00:29Z
[ "python" ]
conditionally parsing json
39,842,046
<p>I am trying to extract a value from a json array using python. How do I get the value for <code>"energy"</code> on a specific day? Here is what the json looks like:</p> <pre><code>{ "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 }, { "year": 2016, "month": 10, "day": 3, "energy": 0.481000 } ], "err_code": 0 } } } </code></pre> <p>So for example, using:</p> <pre><code>parsed_json = json.loads(json) </code></pre> <p>how would I extract the <code>"energy"</code> value for <code>"year":2016, "month":10, "day":2</code>?</p>
-1
2016-10-03T23:37:26Z
39,842,135
<p><code>parsed_json</code> will have a python dict. You can access the <code>day_list</code> array with a simple linear search.</p> <pre><code>def get_energy_value_by_date(obj, year, month, day): for value in obj['emeter']['get_daystat']['day_list']: if value['year'] == year and value['month'] == month and value['day'] == day: return value['energy'] energy = get_energy_value_by_date(parsed_json, 2016, 10, 2) </code></pre>
2
2016-10-03T23:46:28Z
[ "python", "json" ]
conditionally parsing json
39,842,046
<p>I am trying to extract a value from a json array using python. How do I get the value for <code>"energy"</code> on a specific day? Here is what the json looks like:</p> <pre><code>{ "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 }, { "year": 2016, "month": 10, "day": 3, "energy": 0.481000 } ], "err_code": 0 } } } </code></pre> <p>So for example, using:</p> <pre><code>parsed_json = json.loads(json) </code></pre> <p>how would I extract the <code>"energy"</code> value for <code>"year":2016, "month":10, "day":2</code>?</p>
-1
2016-10-03T23:37:26Z
39,842,215
<p>You could do a linear search through the data:</p> <pre><code>def get_energy(data, year, month, day): for date in data['emeter']['get_daystat']['day_list']: if(date['year'] == year and date['month'] == month and date['day'] == day): return date['energy'] json_data = { "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 }, { "year": 2016, "month": 10, "day": 3, "energy": 0.481000 } ], "err_code": 0 } } } print('{:1.6f}'.format(get_energy(json_data, 2016, 10, 2))) # --&gt; 0.349000 </code></pre> <p>If there's no matching date, the function will effectively return <code>None</code>.</p> <p><strong>*Update*</strong></p> <p>If you have a lot of days in the <code>"day_list"</code> <em>and</em> they are ordered (sorted) by date as shown in your example, it would faster to take advantage of that and do a binary search rather than a linear one. Python includes the <a href="https://docs.python.org/2/library/bisect.html#module-bisect" rel="nofollow"><code>bisect</code></a> module, which can be used to do simple binary searches. Unfortunately none of the functions in it take optional arguments for controlling the comparisons like the <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> function does.</p> <p>However this can be overcome by looking at the <a href="https://hg.python.org/cpython/file/2.7/Lib/bisect.py#l67" rel="nofollow">source code</a> for the module and writing your own search function as illustrated below:</p> <pre><code>from datetime import datetime def keyed_bisect_left(a, x, lo=0, hi=None, keyfunc=lambda v: v): """Return the index where to insert item x in list a, assuming a is sorted. Like bisect.bisect_left but allows a keyfunc to extract key from each item. """ x_key = keyfunc(x) if lo &lt; 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo &lt; hi: mid = (lo+hi) // 2 if keyfunc(a[mid]) &lt; x_key: lo = mid+1 else: hi = mid return lo def get_date(d): return datetime(d['year'], d['month'], d['day']) def get_energy2(data, year, month, day): """Locate the first day exactly equal to the given date.""" day_list = data['emeter']['get_daystat']['day_list'] target = {'year': year, 'month': month, 'day': day} i = keyed_bisect_left(day_list, target, keyfunc=get_date) # return energy value if date found if i != len(day_list) and get_date(day_list[i]) == get_date(target): return day_list[i]['energy'] raise ValueError('date not found') print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 1))) print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 2))) print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 3))) print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 4))) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>0.651000 0.349000 0.481000 Traceback (most recent call last): File "conditionally-parsing-json.py", line 67, in &lt;module&gt; print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 4))) # --&gt; ValueError File "conditionally-parsing-json.py", line 62, in get_energy2 raise ValueError('date not found') ValueError: date not found </code></pre>
0
2016-10-03T23:56:18Z
[ "python", "json" ]
How can i avoid the getting this error in pyomo "Error retrieving component Pd[1]: The component has not been constructed."
39,842,072
<p>I am new to pyomo. I am trying to run a simple maximization problem, but i keep getting this error message: <code>Error retrieving component Pd[1]: The component has not been constructed.</code> . Only the last 5 constraints give me this problem, the first three constraints work fine. I'm using this command on the IPython console to run it <code>!pyomo --solver-manager=neos --solver=cbc battpyomo.py battpyomo.dat</code></p> <p>On the data file, I only define the set T and parameter p.</p> <p>set T := 1 2 3 4 5 6 7 8 9;</p> <p>param: p :=<br> 1 51.12<br> 2 48.79<br> 3 39.56<br> 4 36.27<br> 5 36.16<br> 6 34.90<br> 7 33.33<br> 8 21.16<br> 9 24.42;</p> <p>Here's the code for battbyomo.py:</p> <pre><code>from pyomo.environ import * model = AbstractModel() ########Sets######### #Hours model.T = Set() #########Parameters########## #Price model.p = Param(model.T,within=PositiveReals) #Variable OM cost Discharge model.VOMd = Param(initialize=15) #Varaible OM cost Charge model.VOMc = Param(initialize=10) #State of Charge min model.SOCmin = Param(initialize=5) #State of charge max model.SOCmax = Param(initialize=25) #ESS efficiency model.m = Param(initialize=0.99) #Max discharge rate model.Pdmax = Param(initialize=20) #Max charge rate model.Pcmax = Param(initialize=20) #Initial State of Charge model.SOCini = Param(initialize=25) ###########Variables########## #Power discharged model.Pd = Var(model.T, within=NonNegativeIntegers) #Power charged model.Pc= Var(model.T, within=NonNegativeIntegers) #Charging Status model.Uc = Var(model.T, within=NonNegativeIntegers) #Discharging status model.Ud = Var(model.T, within=NonNegativeIntegers) #State of Charge model.SOC = Var(model.T, within=NonNegativeIntegers) #######Objective########## def profit_rule(model): return sum(model.Pd[i]*model.p[i]-model.Pd[i]*model.VOMd-model.Pc[i]*model.p[i]-model.Pc[i]*model.VOMc for i in model.T) model.profit = Objective(rule=profit_rule, sense = maximize) #######Constraints########## def status_rule(model,i): return (model.Ud[i] + model.Uc[i] &lt;= 1) model.status = Constraint(model.T,rule=status_rule) def Cmax_rule(model,i): return model.Pc[i] &lt;= model.Pcmax*model.Uc[i] model.Cmax = Constraint(model.T,rule=Cmax_rule) def Dmax_rule(model,i): return model.Pd[i] &lt;= model.Pdmax*model.Ud[i] model.Dmax = Constraint(model.T,rule=Dmax_rule) def Dlim_rule(module,i): return model.Pd[i] &lt;= model.SOC[i] - model.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) def Clim_rule(module,i): return model.Pc[i] &lt;= model.SOCmax-model.SOC[i] model.Clim = Constraint(model.T,rule=Clim_rule) def Smin_rule(module,i): return model.SOC[i] &gt;= model.SOCmin model.Smin = Constraint(model.T,rule=Smin_rule) def Smax_rule(module,i): return model.SOC[i] &lt;= model.SOCmax model.Smax = Constraint(model.T,rule=Smax_rule) def E_rule(module,i): if i == 1: return model.SOC[i] == model.SOCini + model.Pc[i]*model.m -model.Pd[i] else: return model.SOC[i] == model.SOC[i-1] + model.Pc[i]*model.m - model.Pd[i] model.E = Constraint(model.T,rule=E_rule) </code></pre>
-1
2016-10-03T23:39:59Z
39,853,933
<p>You shouldn't need the very first "import pyomo" line. The only import line you should need is the "from pyomo.environ import *". If this doesn't solve your problem then you should post the data file you're using (or a simplified version of it). Seems like the data isn't being loaded into the Pyomo model correctly.</p>
0
2016-10-04T13:43:02Z
[ "python", "pyomo" ]
How can i avoid the getting this error in pyomo "Error retrieving component Pd[1]: The component has not been constructed."
39,842,072
<p>I am new to pyomo. I am trying to run a simple maximization problem, but i keep getting this error message: <code>Error retrieving component Pd[1]: The component has not been constructed.</code> . Only the last 5 constraints give me this problem, the first three constraints work fine. I'm using this command on the IPython console to run it <code>!pyomo --solver-manager=neos --solver=cbc battpyomo.py battpyomo.dat</code></p> <p>On the data file, I only define the set T and parameter p.</p> <p>set T := 1 2 3 4 5 6 7 8 9;</p> <p>param: p :=<br> 1 51.12<br> 2 48.79<br> 3 39.56<br> 4 36.27<br> 5 36.16<br> 6 34.90<br> 7 33.33<br> 8 21.16<br> 9 24.42;</p> <p>Here's the code for battbyomo.py:</p> <pre><code>from pyomo.environ import * model = AbstractModel() ########Sets######### #Hours model.T = Set() #########Parameters########## #Price model.p = Param(model.T,within=PositiveReals) #Variable OM cost Discharge model.VOMd = Param(initialize=15) #Varaible OM cost Charge model.VOMc = Param(initialize=10) #State of Charge min model.SOCmin = Param(initialize=5) #State of charge max model.SOCmax = Param(initialize=25) #ESS efficiency model.m = Param(initialize=0.99) #Max discharge rate model.Pdmax = Param(initialize=20) #Max charge rate model.Pcmax = Param(initialize=20) #Initial State of Charge model.SOCini = Param(initialize=25) ###########Variables########## #Power discharged model.Pd = Var(model.T, within=NonNegativeIntegers) #Power charged model.Pc= Var(model.T, within=NonNegativeIntegers) #Charging Status model.Uc = Var(model.T, within=NonNegativeIntegers) #Discharging status model.Ud = Var(model.T, within=NonNegativeIntegers) #State of Charge model.SOC = Var(model.T, within=NonNegativeIntegers) #######Objective########## def profit_rule(model): return sum(model.Pd[i]*model.p[i]-model.Pd[i]*model.VOMd-model.Pc[i]*model.p[i]-model.Pc[i]*model.VOMc for i in model.T) model.profit = Objective(rule=profit_rule, sense = maximize) #######Constraints########## def status_rule(model,i): return (model.Ud[i] + model.Uc[i] &lt;= 1) model.status = Constraint(model.T,rule=status_rule) def Cmax_rule(model,i): return model.Pc[i] &lt;= model.Pcmax*model.Uc[i] model.Cmax = Constraint(model.T,rule=Cmax_rule) def Dmax_rule(model,i): return model.Pd[i] &lt;= model.Pdmax*model.Ud[i] model.Dmax = Constraint(model.T,rule=Dmax_rule) def Dlim_rule(module,i): return model.Pd[i] &lt;= model.SOC[i] - model.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) def Clim_rule(module,i): return model.Pc[i] &lt;= model.SOCmax-model.SOC[i] model.Clim = Constraint(model.T,rule=Clim_rule) def Smin_rule(module,i): return model.SOC[i] &gt;= model.SOCmin model.Smin = Constraint(model.T,rule=Smin_rule) def Smax_rule(module,i): return model.SOC[i] &lt;= model.SOCmax model.Smax = Constraint(model.T,rule=Smax_rule) def E_rule(module,i): if i == 1: return model.SOC[i] == model.SOCini + model.Pc[i]*model.m -model.Pd[i] else: return model.SOC[i] == model.SOC[i-1] + model.Pc[i]*model.m - model.Pd[i] model.E = Constraint(model.T,rule=E_rule) </code></pre>
-1
2016-10-03T23:39:59Z
39,856,737
<p>In some of the constraints listed above, the argument in the rule is "module", when "model" is used in the expression e.g.,</p> <pre><code>def Dlim_rule(module,i): return model.Pd[i] &lt;= model.SOC[i] - model.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) </code></pre> <p>The definition of the rule and the constraint should be,</p> <pre><code>def Dlim_rule(model,i): return model.Pd[i] &lt;= model.SOC[i] - model.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) </code></pre> <p>Incidentally, the first argument (for the model object) can be called anything you like. However, the name of the argument must match the use of the model within the rule. For example, this is also valid,</p> <pre><code>def Dlim_rule(m,i): return m.Pd[i] &lt;= m.SOC[i] - m.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) </code></pre>
2
2016-10-04T15:51:39Z
[ "python", "pyomo" ]
Split and Combine Date
39,842,074
<p>I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.</p>
1
2016-10-03T23:40:08Z
39,842,136
<p>You should really be using the <code>dateutil</code> library for this.</p> <pre><code>&gt;&gt;&gt; import dateutil.parser &gt;&gt;&gt; first_date = dateutil.parser.parse('Oct 03 2016') &gt;&gt;&gt; second_date = dateutil.parser.parse('10/3/2016') &gt;&gt;&gt; first_date datetime.datetime(2016, 10, 3, 0, 0) &gt;&gt;&gt; second_date datetime.datetime(2016, 10, 3, 0, 0) &gt;&gt;&gt; first_date == second_date True &gt;&gt;&gt; </code></pre>
6
2016-10-03T23:46:41Z
[ "python" ]
Split and Combine Date
39,842,074
<p>I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.</p>
1
2016-10-03T23:40:08Z
39,842,147
<p>Use <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code></a> module to convert your string to <code>datetime</code> object and then compare both. For example:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; date1 = datetime.strptime('Oct 03 2016', '%b %d %Y') &gt;&gt;&gt; date2 = datetime.strptime('10/3/2016', '%m/%d/%Y') &gt;&gt;&gt; date1 == date2 True </code></pre> <p>Further, you may convert this<code>datetime</code> object to your custom format using <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">datetime.strftime()</a> as:</p> <pre><code>&gt;&gt;&gt; date1.strftime('%d * %B * %Y') '03 * October * 2016' </code></pre> <p>List of all the directives usable for formatting the string are available at the <code>strftime</code> link I mentioned above.</p>
3
2016-10-03T23:48:01Z
[ "python" ]
Topic 12 10 Pyschool Regular Expression
39,842,141
<p>Below is an example from the exercise of regular expression.</p> <pre><code>re.search(regex1, 'a1b22c333d4444').groups() </code></pre> <p>The above expression's required result is </p> <p>('22', '333')</p> <p>What would be the complete expression of <code>regex1 = r"([ ]{2})[^ ]([ ]{ })"</code>?</p>
-2
2016-10-03T23:47:31Z
39,842,966
<p>This looks like you're asking for help on HW. So instead of writing the code for you in the format that is expected, here is another way to get to the solution, so that you can work on it yourself. <code>(\d{2}).+(\d{3})</code>. You can practice your regular expressions here -> <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a></p>
1
2016-10-04T01:41:16Z
[ "python", "regex", "python-3.x" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=17.2ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=12.6ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=11.7ms ... (a bunch more ping responses here) --- e11699.b.akamaiedge.net ping statistics --- 86400 packets transmitted, 86377 received, 0% packet loss, time 86532481ms rtt min/avg/max/mdev = 6.281/18.045/1854.971/28.152 ms, pipe 2 </code></pre> <p>I am very new to python and need help being able to use regex commands to extract only the times between "time=" and "ms"and send it to another text file to look like:</p> <pre><code>11.7 12.6 17.2 ... </code></pre> <p>Any help would be greatly appreciated!</p>
0
2016-10-03T18:55:37Z
39,842,166
<p>Since this seems to come from <a href="/questions/tagged/ping" class="post-tag" title="show questions tagged &#39;ping&#39;" rel="tag">ping</a> command, you could use <a href="/questions/tagged/grep" class="post-tag" title="show questions tagged &#39;grep&#39;" rel="tag">grep</a> like this :</p> <pre><code>grep -oP 'ttl=\d+\s+time=\K[\d\.]+' file </code></pre> <h3>Output :</h3> <pre><code>17.2 12.6 11.7 </code></pre> <h3>Note :</h3> <p>It's very simple to search SO or/and google to use this regex in <em>pure python</em>.</p> <h3>Hint :</h3> <p><a href="http://stackoverflow.com/questions/13542950/support-of-k-in-regex">http://stackoverflow.com/questions/13542950/support-of-k-in-regex</a></p> <h3>Bonus</h3> <p>Because I still have to play with python :</p> <p>(in a <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a> shell) :</p> <pre><code>python2 &lt;&lt;&lt; $'import re\nf = open("/tmp/file", "r")\nfor textline in f.readlines():\n\tmatches = re.finditer("ttl=\d+\s+time=([\d\.]+)ms", textline)\n\tresults = [float(match.group(1).strip()) for match in matches if len(match.group(1).strip())]\n\tif results:\n\t\tprint results[0]\nf.close()\n' </code></pre>
5
2016-10-03T19:02:48Z
[ "text-processing", "python" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=17.2ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=12.6ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=11.7ms ... (a bunch more ping responses here) --- e11699.b.akamaiedge.net ping statistics --- 86400 packets transmitted, 86377 received, 0% packet loss, time 86532481ms rtt min/avg/max/mdev = 6.281/18.045/1854.971/28.152 ms, pipe 2 </code></pre> <p>I am very new to python and need help being able to use regex commands to extract only the times between "time=" and "ms"and send it to another text file to look like:</p> <pre><code>11.7 12.6 17.2 ... </code></pre> <p>Any help would be greatly appreciated!</p>
0
2016-10-03T18:55:37Z
39,842,167
<p>Since you asked for Python, here it is:</p> <pre><code>$ ping -c 4 8.8.8.8 | python -c 'import sys;[ sys.stdout.write(l.split("=")[-1]+"\n") for l in sys.stdin if "time=" in l]' 10.5 ms 9.22 ms 9.37 ms 9.71 ms </code></pre> <p>Note, this has stdout buffering, so you may want to add <code>sys.stdout.flush()</code> . Feel free to convert this from one liner to a script</p>
1
2016-10-03T19:53:31Z
[ "text-processing", "python" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=17.2ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=12.6ms 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=11.7ms ... (a bunch more ping responses here) --- e11699.b.akamaiedge.net ping statistics --- 86400 packets transmitted, 86377 received, 0% packet loss, time 86532481ms rtt min/avg/max/mdev = 6.281/18.045/1854.971/28.152 ms, pipe 2 </code></pre> <p>I am very new to python and need help being able to use regex commands to extract only the times between "time=" and "ms"and send it to another text file to look like:</p> <pre><code>11.7 12.6 17.2 ... </code></pre> <p>Any help would be greatly appreciated!</p>
0
2016-10-03T18:55:37Z
39,847,805
<p>You specified that your data is already in a text file. So asuming that your text file is called <code>data.txt</code></p> <pre><code>#we will be using the regular expression library for this example import re #open the "data.txt" (named data_file in a scope) with open("data.txt") as data_file: #read the text from the data_file into ping_data ping_data = data_file.read() found_data = re.findall('time=(.*)ms', ping_data) with open('found.txt', 'w') as found_file: for pattern in found_data: found_file.write(pattern+"\n") </code></pre> <p>This fill output a file called <code>found.txt</code> with the following:</p> <pre><code>17.2 12.6 11.7 </code></pre> <p>In the example we just open your data.txt file. Then read the data form it. Then find all the occurrences of the regular expression pattern that will return the data you are looking for.</p> <p><code>time=(.*)ms</code> means *a string of any size between the letters <code>time=</code> and <code>ms</code></p> <p>Then after we have found the patern we simply write it to another file called <code>found.txt</code>, writing one line at a time until its complete.</p>
0
2016-10-04T08:41:50Z
[ "text-processing", "python" ]
pip install for Python 3 in virtualenv on Mac OSX?
39,842,197
<p>I can <code>pip install</code> and <code>import</code> just about any package on my Mac in a virtual environment, doing the following:</p> <p>Setting up the virtual environment:</p> <pre><code>Last login: Mon Oct 3 18:47:06 on ttys000 me-MacBook-Pro-3:~ me$ cd /Users/me/Desktop/ me-MacBook-Pro-3:Desktop me$ virtualenv env New python executable in /Users/me/Desktop/env/bin/python Installing setuptools, pip, wheel...done. me-MacBook-Pro-3:Desktop me$ source env/bin/activate </code></pre> <p>Let's <code>pip install</code> pandas:</p> <pre><code>(env) me-MacBook-Pro-3:Desktop me$ pip install pandas Collecting pandas Using cached pandas-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Collecting pytz&gt;=2011k (from pandas) Using cached pytz-2016.7-py2.py3-none-any.whl Collecting python-dateutil (from pandas) Using cached python_dateutil-2.5.3-py2.py3-none-any.whl Collecting numpy&gt;=1.7.0 (from pandas) Using cached numpy-1.11.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Collecting six&gt;=1.5 (from python-dateutil-&gt;pandas) Using cached six-1.10.0-py2.py3-none-any.whl Installing collected packages: pytz, six, python-dateutil, numpy, pandas Successfully installed numpy-1.11.1 pandas-0.19.0 python-dateutil-2.5.3 pytz-2016.7 six-1.10.0 </code></pre> <p>Great! Now, let's see if it works in Python 2.7:</p> <pre><code>(env) me-MacBook-Pro-3:Desktop me$ python Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pandas &gt;&gt;&gt; exit() </code></pre> <p><code>pandas</code> loaded in 2.7, now let's try 3.5:</p> <pre><code>(env) me-MacBook-Pro-3:Desktop me$ python3 Python 3.5.0a4 (v3.5.0a4:413e0e0004f4, Apr 19 2015, 14:19:25) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pandas Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'pandas' &gt;&gt;&gt; </code></pre> <p>:(</p> <p>I'm running OSX El Capitan 10.11.6. How can I import non-builtin modules in a virtual environment? I really would rather use Python 3...</p>
0
2016-10-03T23:53:49Z
39,842,683
<p>Try using <code>virtualenv --python=$(which python3) env</code> to create the virtual environment. </p> <p>When you create a virtualenv by default it uses the python binary it was installed with. So if you did <code>pip install virtualenv</code> on a system where python2.7 was installed first, then virtualenv will use python2.7 by default. You'll want to create separate virtual environments for different python versions. </p>
2
2016-10-04T00:58:03Z
[ "python", "osx", "pip" ]