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
Issue with pattern program using loops
39,931,798
<p>I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring ...
0
2016-10-08T11:27:11Z
39,931,979
<p>Often in Python you don't need any loops</p> <pre><code>lines = int(input('Lines= ')) cheers = int(input('Cheers= ')) line = ' BUDDY '.join(['GO']*cheers) for i in range(cheers): print(' '*(i*3) + line) </code></pre>
1
2016-10-08T11:48:58Z
[ "python", "python-2.7", "design-patterns" ]
Issue with pattern program using loops
39,931,798
<p>I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring ...
0
2016-10-08T11:27:11Z
39,932,051
<p>Try this.</p> <pre><code>def greet(lines, cheers): for i in range (lines): output = (" ") * i + "Go" for j in range (cheers): if cheers == 1: print output break output += "Budddy Go" print output </code></pre> <p>Hope this helps.<...
1
2016-10-08T11:57:14Z
[ "python", "python-2.7", "design-patterns" ]
JSON sub for loop produces KeyError, but key exists
39,931,910
<p>I'm trying to add the JSON output below into a dictionary, to be saved into a SQL database.</p> <pre><code>{'Parkirisca': [ { 'ID_Parkirisca': 2, 'zasedenost': { 'Cas': '2016-10-08 13:17:00', 'Cas_timestamp': 1475925420, 'ID_ParkiriscaNC': 9, ...
0
2016-10-08T11:40:30Z
39,932,458
<p>I fixed up your code:</p> <ol> <li>Added required imports.</li> <li>Fixed the <code>pprint savetodb</code> line which isn't valid Python.</li> <li>Didn't try to iterate over <code>carpark['zasedenost']</code>.</li> </ol> <p>I then added another <code>pprint</code> statement in the <code>for</code> loop to see what...
1
2016-10-08T12:39:40Z
[ "python", "json", "list", "for-loop", "dictionary" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if ...
0
2016-10-08T11:40:36Z
39,931,942
<p>Change to :</p> <pre><code>snumA = random.choice([4,8,3]) </code></pre> <p>which will give you an <code>int</code> instead of a <code>list</code>. To understand better the error here is that you try to use lists (cause <code>random.sample</code> returns a list type result) as integers to make arithmetic operations...
4
2016-10-08T11:44:13Z
[ "python" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if ...
0
2016-10-08T11:40:36Z
39,932,129
<p>The problem is: <code>snumA = random.sample([4,8,3], 1)</code> returns a list of one element (for example: [3] ). What you can do instead is: Either use <code>snumA = random.choice([4,8,3])</code> which returns directly an integer. Or you get hold of the first element of your list with <code>snumA[0]</code> or direc...
2
2016-10-08T12:05:17Z
[ "python" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if ...
0
2016-10-08T11:40:36Z
39,932,182
<ol> <li>As suggested before, use random.choice</li> <li>bnumA is not defined. The code below assumes you meant snumB</li> </ol> <p>So the code you are looking for might be:</p> <pre><code>import random snumA = random.choice([4,8,3]) snumB = random.choice([7,2,6]) snumC = random.choice([1,5,9]) operators = {'+':'Pl...
1
2016-10-08T12:10:34Z
[ "python" ]
Old (sklearn 0.17) GMM, DPGM, VBGMM vs new (sklearn 0.18) GaussianMixture and BayesianGaussianMixture
39,931,922
<p>In previous scikit-learn version (0.1.17) I used the following code to automatically determine best Gaussian mixture models and optimize hyperparameters (alpha, covariance type, bic) for unsupervised clustering.</p> <pre><code># Gaussian Mixture Model try: # Determine the most suitable covariance_type ...
0
2016-10-08T11:41:11Z
39,935,265
<p>The BIC score is still available for the classical / EM implementation of GMMs as implemented in the GaussianMixture class.</p> <p>The BayesianGaussianMixture class can automatically tune the number of effective components (n_components should just be big enough) for a given value of <code>alpha</code>.</p> <p>You...
0
2016-10-08T17:27:08Z
[ "python", "scikit-learn", "cluster-analysis", "gaussian", "unsupervised-learning" ]
Create a DTM from large corpus
39,931,941
<p>I have a set of texts contained in a list, which I loaded from a csv file</p> <p><code>texts=['this is text1', 'this would be text2', 'here we have text3']</code></p> <p>and I would like to create a document-term matrix, by using <em>stemmed words</em>. I have also stemmed them to have:</p> <p><code>[['text1'], [...
1
2016-10-08T11:44:08Z
39,933,594
<p>Why don't you use <code>sklearn</code>? The <code>CountVectorizer()</code> method <strong>converts a collection of text documents to a matrix of token counts</strong>. What's more it gives a sparse representation of the counts using <code>scipy</code>.</p> <p>You can either give your raw entries to the method or pr...
1
2016-10-08T14:31:50Z
[ "python", "pandas", "scikit-learn", "nltk" ]
How to build python code for mac os x using cx_freeze on windows?
39,932,044
<p>I have installed cx_freeze and it works like a charm to build .exe but I want to make executable file of my python program for mac os x using windows 7. Can you guide me how I can do it using cx_freeze or any other application.</p> <p>I use following code to build .exe</p> <pre><code>from cx_Freeze import setup, E...
0
2016-10-08T11:56:20Z
39,932,119
<p>There is no simple way. You need to compile your app on OS X to include the OS X specific libraries (the shared libraries and other dependencies). </p> <p>You need to do this on OS X. </p>
0
2016-10-08T12:04:33Z
[ "python", "windows", "osx", "cx-freeze" ]
How to build python code for mac os x using cx_freeze on windows?
39,932,044
<p>I have installed cx_freeze and it works like a charm to build .exe but I want to make executable file of my python program for mac os x using windows 7. Can you guide me how I can do it using cx_freeze or any other application.</p> <p>I use following code to build .exe</p> <pre><code>from cx_Freeze import setup, E...
0
2016-10-08T11:56:20Z
39,932,192
<p>Install VirtalBox.</p> <p>Then follow this guide to install an OS X virtual machine: <a href="http://lifehacker.com/5938332/how-to-run-mac-os-x-on-any-windows-pc-using-virtualbox" rel="nofollow">http://lifehacker.com/5938332/how-to-run-mac-os-x-on-any-windows-pc-using-virtualbox</a></p> <p>Then you will be able to...
0
2016-10-08T12:11:20Z
[ "python", "windows", "osx", "cx-freeze" ]
Mongodb aggregate out of memory
39,932,096
<p>I'm using mongodb aggregate to sample documents from a large collection.</p> <p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/aggregation/sample/</a></p> <p>After making several consecutive calls, I see the memory ...
1
2016-10-08T12:02:29Z
39,934,310
<p>The reason you are asking this is because you don't know how the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow"><code>$sample</code></a> operator works. As mentioned in the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/#behavior" rel="...
1
2016-10-08T15:46:23Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]
Mongodb aggregate out of memory
39,932,096
<p>I'm using mongodb aggregate to sample documents from a large collection.</p> <p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/aggregation/sample/</a></p> <p>After making several consecutive calls, I see the memory ...
1
2016-10-08T12:02:29Z
39,934,839
<p>It turns out the issue was the storage engine cache. I'm using an EC2 instance, and it resulted in OOM error there. I've been able to solve it by assigning a smaller cache size like this:</p> <pre><code>mongod --dbpath /a/path/to/db --logpath /a/path/to/log --storageEngine wiredTiger --wiredTigerEngineConfigString=...
0
2016-10-08T16:43:33Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]
Global variables code confusion
39,932,120
<p>I am having trouble getting data input from one class to another and I cant seem to get the global function to work. The part i need help with is in the last function but it only works if you have the whole code.</p> <pre><code>import tkinter as tk import os self = tk TITLE_FONT = ("AmericanTypewriter", 18, "bold"...
-3
2016-10-08T12:04:40Z
39,932,375
<p>If you want to use global variables, you need to do this:</p> <pre><code>var1 = &lt;some value&gt; var2 = &lt;some other value&gt; s1 = &lt;yet another value here&gt; # then create your classes class Whatever(tk.whatever_you_want): def __init__(self, arg1, arg2, whatever_arg): global var1 #whis tells...
0
2016-10-08T12:31:12Z
[ "python", "python-3.x", "global-variables" ]
Django Custom Admin Form bulk save implmentation
39,932,134
<p>I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows.</p> <p>This is my Admin class:</p> <pre><code>class EmployeeAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director') search_fields = ['user...
0
2016-10-08T12:05:38Z
39,932,272
<p>You should just add the <code>super().save()</code> to the the end of the function:</p> <pre><code>def save(self, *args, commit=True, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CS...
1
2016-10-08T12:19:23Z
[ "python", "django", "csv" ]
Make the background of an image transparant in Pygame with convert_alpha
39,932,138
<p>I am trying to make the background of an image transparant in a Pygame script. Now the background in my game is black, instead of transparant. I read somewhere else that I could use <code>convert_alpha</code>, but it doesn't seem to work.</p> <p>Here is (the relevant part of) my code:</p> <pre><code>import PIL gam...
0
2016-10-08T12:06:16Z
39,938,626
<p>To make an image transparent you first need an image with alpha values. Be sure that it meets this criteria! I noticed that my images doesn't save the alpha values when saving as bmp. Apparently, <a href="http://www.ehow.com/how_12224322_make-bmp-transparent.html" rel="nofollow">the bmp format do not have native tra...
1
2016-10-09T00:00:41Z
[ "python", "pygame" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows...
2
2016-10-08T12:15:48Z
39,932,312
<p>According to <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show</a> , the <code>plt.show()</code> itself doesn't know about the data, you need to pass the data as parameters.</p> <p>What you are seeing should be ...
1
2016-10-08T12:23:17Z
[ "python", "python-2.7" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows...
2
2016-10-08T12:15:48Z
39,932,362
<p>From the pandas docs on <a href="https://github.com/pydata/pandas/blob/cebc70cc277462176edea73bb71eaad9f83e9f47/doc/source/visualization.rst#basic-plotting-plot" rel="nofollow">plotting</a>:</p> <blockquote> <p>The <code>plot</code> method on Series and DataFrame is just a simple wrapper around :meth:<code>plt....
2
2016-10-08T12:29:36Z
[ "python", "python-2.7" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows...
2
2016-10-08T12:15:48Z
39,932,541
<p>Matplotlib has two "interfaces": a <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html" rel="nofollow">Matlab-style interface</a> and an <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html" rel="nofollow">object-oriented interface</a>. </p> <p>Plotting with the Matlab-style i...
3
2016-10-08T12:47:15Z
[ "python", "python-2.7" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[d...
2
2016-10-08T12:38:15Z
39,932,508
<p>Just <code>append</code> the item to the list. Note, BTW, that <code>range</code> starts with <code>0</code> if you don't specify the start value and treats the end value as an <strong>exclusive</strong> border:</p> <pre><code>x = [] for i in range(1, 4): x.append(dict['w' + str(i)]) </code></pre>
0
2016-10-08T12:43:44Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[d...
2
2016-10-08T12:38:15Z
39,932,509
<p>One approach would be to get the argsort indices based on the keys and sort the elements/values out of the dictionary using those indices, like so -</p> <pre><code>np.take(dict.values(),np.argsort(dict.keys())) </code></pre> <p>If you need a list as the output, add <a href="http://docs.scipy.org/doc/numpy/referenc...
1
2016-10-08T12:43:46Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[d...
2
2016-10-08T12:38:15Z
39,932,524
<p>Comprehension:</p> <pre><code># using name as "dict" is not proper use "_dict" otherwise. dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [dict["w"+str(i)] for i in range(1, 4)] </code></pre> <p>gives output:</p> <pre><code>[[1, 2, 3], [4, 5, 6], [7, 8]] </code></pre>
2
2016-10-08T12:45:37Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[d...
2
2016-10-08T12:38:15Z
39,932,565
<p>If you mean lists and not dictionarys, then you're looking for the zip command.</p> <p>Zip (w1,w2,w3)</p>
0
2016-10-08T12:50:04Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
How do I write a program out of provided unittest
39,932,472
<p>I have a unittests for a program. Being new to test driven development, how can I generate a program from the given tests</p> <p>For example I have this test:</p> <pre><code>class MaxMinTest(TestCase): """docstring for MaxMinTest""" def test_find_max_min_four(self): self.assertListEqual([1, 4], ...
0
2016-10-08T12:41:02Z
39,932,582
<p>Without giving you the answer to the code that would make these tests pass, your approach can be something like this:</p> <ul> <li><p>What are you testing? </p></li> <li><p>What does this function take, and what does it return?</p></li> <li><p>How do I make <strong>one</strong> test pass? Once I make one test pass,...
1
2016-10-08T12:51:24Z
[ "python", "python-2.7", "unit-testing", "tdd" ]
Comparing two columns in different file and printing match if difference between record in a columns less than or equal to 0.001
39,932,484
<p>I have two text files, say file1.txt contains something like </p> <pre><code>100.145 10.0728 100.298 10.04 100.212 10.0286 </code></pre> <p>and file2.txt contains something like </p> <pre><code>100.223 8.92739 100.209 9.04269 100.084 9.08411 </code></pre> <p>I want to compare column 1 and column 2 of both files ...
0
2016-10-08T12:41:59Z
39,932,607
<p>Just read both files, split by line break, split those lines by spaces and then loop over the first files lines and for each line check whether the second files line at this position matches your condition.</p> <pre class="lang-py prettyprint-override"><code>with open("file1.txt", "r") as f: f1_content = f.read()...
1
2016-10-08T12:54:18Z
[ "python", "awk" ]
Comparing two columns in different file and printing match if difference between record in a columns less than or equal to 0.001
39,932,484
<p>I have two text files, say file1.txt contains something like </p> <pre><code>100.145 10.0728 100.298 10.04 100.212 10.0286 </code></pre> <p>and file2.txt contains something like </p> <pre><code>100.223 8.92739 100.209 9.04269 100.084 9.08411 </code></pre> <p>I want to compare column 1 and column 2 of both files ...
0
2016-10-08T12:41:59Z
39,932,947
<p>I would use <code>paste</code> to combine the files and then let <code>awk</code> do the rest:</p> <pre><code>paste file1.txt file2.txt | awk ' function abs(v) {return v &lt; 0 ? -v : v} abs($1-$3) &lt;= lim &amp;&amp; abs($2-$4) &lt;= lim ' lim=0.001 </code></pre> <p><code>abs</code> function definition copie...
0
2016-10-08T13:28:43Z
[ "python", "awk" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <...
2
2016-10-08T12:42:13Z
39,932,532
<p>Sounds like <code>zip</code> is your friend:</p> <pre><code>&gt;&gt;&gt; zip(*tuplelist) [('a', 6, 0), ('b', 3, 4), ('c', 9, 5), ('d', 11, 6)] </code></pre> <p>You can use <code>zip</code> a little bit like a matrix transpose in math. Anyway, for your situation, we can do:</p> <pre><code>for x in zip(*tuplelist)...
3
2016-10-08T12:46:26Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <...
2
2016-10-08T12:42:13Z
39,932,592
<p>Just simpley use tuple and list indices. If you only want one value from one specfic place in a container, don't use a loop, just use indices.</p> <pre><code>res = (tuplelist[0][3],'has_val', tuplelist[1][3]) </code></pre> <p>Full program:</p> <pre><code>tuplelist = [('a', 'b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5,...
1
2016-10-08T12:52:54Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <...
2
2016-10-08T12:42:13Z
39,932,645
<p>Firstly, Don't name your variable as <code>str</code> as it shadows the builtin function. </p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] s = 'has_val' </code></pre> <p>Now coming to your issue, It's aesthetic to have the first row out as a header row. Also note that, I've used the <...
3
2016-10-08T12:58:21Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <...
2
2016-10-08T12:42:13Z
39,932,651
<p>zip() can work for your problem</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] tuplelist_withposition=zip(tuplelist[0],tuplelist[1],tuplelist[2]) s = 'has_val' for i in tuplelist_withposition: rel = (i[0],s,i[1]) print rel rel=(i[0],s,i[2]) print rel </code></pre...
2
2016-10-08T12:58:30Z
[ "python", "list", "python-3.x", "tuples" ]
Dynamically updating the PYTHONPATH prevents .pyc update
39,932,498
<p>To allow myself to have a clear filestructure in my project i am using the following code snippet to dynamically add the project main folder to the PYTHONPATH and therefore assure that I can import files even from above a files location.</p> <pre class="lang-py prettyprint-override"><code>import sys import os sys.p...
0
2016-10-08T12:43:06Z
39,932,583
<p>You could try to make python not write those *.pyc files.</p> <p><a href="http://stackoverflow.com/questions/154443/how-to-avoid-pyc-files">How to avoid .pyc files?</a></p> <p>For large projects this would matter slightly from a performance perspective. It's possible that you don't care about that, and then you ca...
1
2016-10-08T12:51:50Z
[ "python", "pythonpath", "pyc" ]
Dynamically updating the PYTHONPATH prevents .pyc update
39,932,498
<p>To allow myself to have a clear filestructure in my project i am using the following code snippet to dynamically add the project main folder to the PYTHONPATH and therefore assure that I can import files even from above a files location.</p> <pre class="lang-py prettyprint-override"><code>import sys import os sys.p...
0
2016-10-08T12:43:06Z
39,932,711
<p>Adding the path of an already imported module can get you into trouble if module names are no longer unique. Consider that you do <code>import foo</code>, which adds its parent package <code>bar</code> to <code>sys.path</code> - it's now possible to also do <code>import bar.foo</code>. Python will consider both to b...
0
2016-10-08T13:05:49Z
[ "python", "pythonpath", "pyc" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me wh...
-3
2016-10-08T13:02:37Z
39,932,689
<p>You forget "()":</p> <pre><code> object1.test() </code></pre> <p>Remember the methods need to be called with the brackets, for example in the propierties are not need it.</p>
1
2016-10-08T13:03:50Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me wh...
-3
2016-10-08T13:02:37Z
39,932,705
<p>specifying a method with the parentheses just returns a reference to it. In order to call it, you need to have <code>()</code> (and optionally, any arguments) after it:</p> <pre><code>object1.test() </code></pre>
1
2016-10-08T13:05:11Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me wh...
-3
2016-10-08T13:02:37Z
39,932,726
<p>add parentheses '()' to the method name where you're calling it.</p> <p>object1.test()</p>
1
2016-10-08T13:08:25Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me wh...
-3
2016-10-08T13:02:37Z
39,932,755
<p>To call a function it requires '()'. Without these it's just a reference not a call.</p> <pre><code>object1.test () </code></pre> <p>Hope this helps.</p>
1
2016-10-08T13:11:07Z
[ "python", "python-2.7", "python-3.x" ]
pandas unique values multiple columns different dtypes
39,932,685
<p>Similar to <a href="http://stackoverflow.com/questions/26977076/pandas-unique-values-multiple-columns">pandas unique values multiple columns</a> I want to count the number of unique values per column. However, as the dtypes differ I get the following error: <a href="http://i.stack.imgur.com/78Fd5.jpg" rel="nofollow"...
0
2016-10-08T13:03:17Z
39,933,598
<p>Use <code>apply</code> and <code>np.unique</code> to grab the unique values in each column and take its <code>size</code>:</p> <pre><code>small[['TARGET','title']].apply(lambda x: np.unique(x).size) </code></pre> <p>Thanks!</p>
1
2016-10-08T14:32:14Z
[ "python", "pandas", "unique" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p...
-2
2016-10-08T13:14:36Z
39,932,832
<p>Your code is not completely right. You're slicing the list with the items in the list, not with indices. Luckily, this did not throw any error because the items in the list are within the bounds of the list's indices or rather <em>slicing</em> does not raise errors, when done correclty, irrespective of start and/or ...
1
2016-10-08T13:17:21Z
[ "python", "python-3.x" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p...
-2
2016-10-08T13:14:36Z
39,932,862
<p>You're getting wrong result because you're iterating on the value of elements not on the index of elements of elements. Try following code</p> <pre><code>def array123(nums): for i in range(len(nums)-2): if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p>And remember to gi...
0
2016-10-08T13:20:56Z
[ "python", "python-3.x" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p...
-2
2016-10-08T13:14:36Z
39,932,905
<p>It should be like this.</p> <pre><code>def array123(nums): for i in range(len(nums)): if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p>Try this. Hope this helps. :)</p>
1
2016-10-08T13:24:30Z
[ "python", "python-3.x" ]
Regular expression to extract data from news page
39,932,825
<p>Hi I'm running python regular expression to extract some data from news pages, however when it is displayed the code produces brackets and apostrophes in the output. For example this is my code:</p> <pre><code>description_title = findall('&lt;item&gt;[\s]*&lt;title[^&gt;]*&gt;(.*?)&lt;\/title&gt;[\s]*&lt;descriptio...
0
2016-10-08T13:16:56Z
39,932,856
<p>By using <a href="https://docs.python.org/2/library/functions.html#str" rel="nofollow"><code>str</code></a>, you're printing a Python string representation of <code>description_title</code> (which is a <code>list</code> of length 1). Try without the <code>str</code>:</p> <pre><code>'&lt;h3 align="Center"&gt;' + de...
1
2016-10-08T13:20:20Z
[ "python", "html", "regex" ]
Python redis rpop is resultng b'value' list structure
39,932,873
<p>I am working on a simple redis and flask project using docker compose. my flask manuplates redis list structure using lpush, rpop. It worked fine until i was playing with commands like brpop which now made all my results b'value'. I tried to work with the first commands only, but somehow the b'value' output keeps co...
0
2016-10-08T13:22:37Z
39,943,518
<p>It seems that redis strings are Python bytes strings (see the documentation about <a href="http://redis.io/topics/data-types" rel="nofollow">Data Types</a>).</p> <p>So, I think there is a automatic conversion from Unicode to Bytes in Python 3 (and maybe in Python 2 too).</p> <p>To work with Unicode string, you can...
0
2016-10-09T12:17:07Z
[ "python", "list", "redis", "docker-compose" ]
Aide in modifying this code removing the ' * ' operator and using while loops instead?
39,932,875
<p>How can I modify my code and remove the ' * ' operator which I have used to multiply strings and use while loops instead of it to produce the same pattern?</p> <pre><code>i = 1 x = 1 while i &lt;= 4: print "v"*x print "v"*x x = x+1 i+=1 print "v"*5 b = 4 while b&gt;=1: print "v"*b print "v"*...
-3
2016-10-08T13:22:41Z
39,933,005
<p>Perhaps consider using the <code>range</code> function and a <code>for-loop</code> within your while loop? The <code>range(stop, end)</code> function returns an array with integers from <code>stop</code> (inclusive) to <code>end</code> (exclusive). For ex: <code>range(0,3)</code> returns <code>[0, 1, 2]</code>. So i...
0
2016-10-08T13:34:17Z
[ "python", "python-2.7", "while-loop" ]
Aide in modifying this code removing the ' * ' operator and using while loops instead?
39,932,875
<p>How can I modify my code and remove the ' * ' operator which I have used to multiply strings and use while loops instead of it to produce the same pattern?</p> <pre><code>i = 1 x = 1 while i &lt;= 4: print "v"*x print "v"*x x = x+1 i+=1 print "v"*5 b = 4 while b&gt;=1: print "v"*b print "v"*...
-3
2016-10-08T13:22:41Z
39,933,133
<p>Hey this is the simplest way of doing this.</p> <pre><code>length = 4 i = 0 output = "v" for j in range(length-1): print output + "\n" + output output += "v" print output for j in range(length): output = output[:-1] print output + "\n" + output </code></pre> <p>Try this out. Hope this helps.</p> <...
1
2016-10-08T13:44:33Z
[ "python", "python-2.7", "while-loop" ]
python re.search quantifier
39,932,949
<p>I have this:-</p> <pre><code>re.search("^[47]{2:}$", '447447') </code></pre> <p>... and was expecting it to return True. But somehow it does not.</p> <p>How come? My understanding is that it was suppose to match any number which has any combination of 4 or 7, with at least 2 digits. Is that correct?</p>
-1
2016-10-08T13:28:52Z
39,932,990
<p>It should probably be <code>"^[47]{2,}$"</code>.</p> <p>I visit the <a href="https://docs.python.org/2/library/re.html#regular-expression-syntax" rel="nofollow">regular expression syntax</a> page quite often, because I find it hard to remember all of the little tricks for building regexes.</p>
3
2016-10-08T13:32:59Z
[ "python", "regex", "search" ]
python re.search quantifier
39,932,949
<p>I have this:-</p> <pre><code>re.search("^[47]{2:}$", '447447') </code></pre> <p>... and was expecting it to return True. But somehow it does not.</p> <p>How come? My understanding is that it was suppose to match any number which has any combination of 4 or 7, with at least 2 digits. Is that correct?</p>
-1
2016-10-08T13:28:52Z
39,933,011
<p>The syntax is <code>{m,n}</code> where <em>n</em> could be omitted.</p> <p>Fix:</p> <pre><code>re.search("^[47]{2,}$", '447447') </code></pre> <p>See RegEx syntax: <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">https://docs.python.org/3/library/re.html#regular-express...
2
2016-10-08T13:34:56Z
[ "python", "regex", "search" ]
Python JWT and RSA
39,932,977
<p>I would like to learn about creating JWT using RSA public and private key. I am a beginner to learn securing my services. I am using pyjwt right now. I got something error with my testing, here it is:</p> <p>SAMPLEKEY:</p> <pre><code>privatekey = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCkC2AfenNMfrU4oMfMZt...
0
2016-10-08T13:31:47Z
39,933,122
<p>This issue is reported on GitHub here: <a href="https://github.com/jpadilla/pyjwt/issues/81" rel="nofollow">https://github.com/jpadilla/pyjwt/issues/81</a></p> <p>And marked as "closed". </p>
0
2016-10-08T13:43:48Z
[ "python", "rsa", "pyjwt" ]
Python JWT and RSA
39,932,977
<p>I would like to learn about creating JWT using RSA public and private key. I am a beginner to learn securing my services. I am using pyjwt right now. I got something error with my testing, here it is:</p> <p>SAMPLEKEY:</p> <pre><code>privatekey = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCkC2AfenNMfrU4oMfMZt...
0
2016-10-08T13:31:47Z
39,933,301
<p>Basically you'll want to switch the keys, use the private key for "encoding" (signing) and public for "decoding" (verification).</p>
0
2016-10-08T14:01:57Z
[ "python", "rsa", "pyjwt" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,164
<p>Try to use commands libray.</p> <pre><code>import commands commands.getoutput("cd $BASEDIR./Desktop") </code></pre>
0
2016-10-08T13:48:04Z
[ "python" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,181
<p>You might get some use out of <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser</code></a> or <a href="https://docs.python.org/2/library/os.path.html#os.path.expandvars" rel="nofollow"><code>os.path.expandvars</code></a>:</p> <pre><code>&gt;&gt;&gt; ...
1
2016-10-08T13:49:37Z
[ "python" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,304
<p>You can read environment variables directly from <code>os.environ</code>:</p> <pre><code>import os basedir = os.environ.get('BASEDIR') </code></pre> <p>To construct a path reliably, the <code>os</code> module provides <code>os.path.join</code>. You should also provide a fallback if the variable is undefined. This ...
1
2016-10-08T14:02:07Z
[ "python" ]
Mac beeps when I type end parantheses in commented block of Python
39,933,160
<p>Why, when I type an end parantheses in a commented out area in IDLE, does mac sound the error beep, and how can I stop it?</p>
0
2016-10-08T13:47:47Z
39,938,365
<p>Various programs, including IDLE, sometimes ask the computer to 'beep' when the user does something that the program considers an error. In general, to not hear a beep, you can 1) stop doing whatever provokes the beep, 2) turn your speaker down or off, or 3) plug in earphones and not wear them while editing.</p>
0
2016-10-08T23:14:02Z
[ "python", "osx", "comments", "python-idle", "beep" ]
Selection Sort-array sorting
39,933,331
<p>When I run it only the first smallest number gets sorted. Is the problem somewhere in the loops?</p> <pre><code>def selectionSort(A): n=len(A) print(n) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if...
-1
2016-10-08T14:04:31Z
39,933,403
<p>There are actually two issues:</p> <ol> <li>Your second <code>if</code> should be outside the inner <code>for</code> loop.</li> <li>And your outer and inner loop should be iterating till <code>n-1</code> and <code>n</code> respectively, instead of <code>n-2</code> and <code>n-1</code>.</li> </ol> <hr> <p>Hence, y...
0
2016-10-08T14:12:19Z
[ "python" ]
Selection Sort-array sorting
39,933,331
<p>When I run it only the first smallest number gets sorted. Is the problem somewhere in the loops?</p> <pre><code>def selectionSort(A): n=len(A) print(n) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if...
-1
2016-10-08T14:04:31Z
39,933,409
<p>Yes the problem is in the swapping part of your code, it needs to placed after inner for-loop</p> <pre><code>def selectionSort(A): n = len(A) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if i!=mini: ...
0
2016-10-08T14:12:41Z
[ "python" ]
Is it possible to mix literal words and tags in NLTK regex
39,933,493
<p>I'm experimenting with NLTK to help me parse some text. As an example I have:</p> <pre><code>1 Robins Drive owned by Gregg S. Smith was sold to TeStER, LLC of 494 Bridge Avenue, Suite 101-308, Sheltville AZ 02997 for $27,000.00. </code></pre> <p>using:</p> <pre><code>words =pos_tag(word_tokenize(sentence)) </code...
0
2016-10-08T14:21:43Z
39,935,194
<p>if you combine each word and tag and then use <code>RegEx</code> to look for certain sequences of PoS tags you can get the results you are looking for.</p> <p>for example, using the <code>words</code> variable you have defined</p> <pre><code>joined = ' '.join([w+"&lt;"+t+"&gt;" for w,t in words]) </code></pre> <p...
1
2016-10-08T17:20:39Z
[ "python", "nltk" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,555
<p>Given you are trying to alternate the sign you can use the fact that <code>(-1)**n</code> also alternates the sign. But you want a negative when <code>n</code> is even you will need <code>(-1)**(n-1)</code>:</p> <pre><code>&gt;&gt;&gt; list(n*(-1)**(n-1) for n in range(1, 11)) [1, -2, 3, -4, 5, -6, 7, -8, 9, -10] &...
2
2016-10-08T14:28:24Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,560
<p>You can use a generator expression like </p> <pre><code>&gt;&gt;&gt; sum(v if v%2 else -v for v in range(11)) -5 </code></pre> <p>Here we check if the index is even or odd and add the number accordingly. </p> <p>Another way can be using the <code>zip</code> builtin, But this works only for an even range. </p> <p...
2
2016-10-08T14:28:41Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,573
<p>your code need a very small change:</p> <pre><code>i = 1 sum = 0 sign = 1 while i&lt;= 10: sum = sum + sign * i sign = sign * -1 i = i + 1 print(sum) </code></pre> <p>There are more pythonic ways to do what you requested - but they will require a little more knowledge..</p>
1
2016-10-08T14:29:48Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,582
<p>You should do like:</p> <pre><code>i = 1 my_sum = 0 while i&lt;= 10: if i % 2: # True, if i is divisible by 2 my_sum -= i else: my_sum += i i += 1 # same as i = i + 1 </code></pre> <p>Some other alternative approaches:</p> <pre><code>&gt;&gt;&gt; sum((i if i % 2 else -i) for i in r...
1
2016-10-08T14:30:32Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,631
<p>It can also be seen as <code>sum of odd</code> minus <code>sum of even</code></p> <pre><code>sum(range(1, 11, 2)) - sum(range(2, 11, 2)) </code></pre>
1
2016-10-08T14:36:15Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,634
<p>To expand this to a much easier, linear solution that works for any n series like this:</p> <pre><code>def sum_subtract(n): return n // 2 * -1 + n % 2 * n </code></pre> <p>Every pair of numbers (1 - 2) + (3 - 4) + etc. equals -1, so you just floor divide by 2 and multiply by -1. Next if there is an odd number ...
1
2016-10-08T14:36:27Z
[ "python", "list" ]
Import serializer in models.py : Django rest framwork
39,933,538
<p>My one model class having following models,</p> <p><strong>NewsfeedModel.py</strong></p> <pre><code>class NewsFeed(models.Model): class NewsStatus(models.Model): class NewsImage(models.Model): </code></pre> <p>this is my serializers.py file</p> <pre><code>from MadhaparGamApps.AppModels.NewsfeedModel import New...
0
2016-10-08T14:25:51Z
39,934,309
<p>It seems like you are trying to Import NewsFeed model to itself.</p> <p>The flow of a django-rest-framework looks like this:</p> <p>Model > Serializer > View</p> <p>After getting your serializers done all you need to do Is to import the models and serializers into the views.py file, in which you will create class...
0
2016-10-08T15:46:17Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
Import serializer in models.py : Django rest framwork
39,933,538
<p>My one model class having following models,</p> <p><strong>NewsfeedModel.py</strong></p> <pre><code>class NewsFeed(models.Model): class NewsStatus(models.Model): class NewsImage(models.Model): </code></pre> <p>this is my serializers.py file</p> <pre><code>from MadhaparGamApps.AppModels.NewsfeedModel import New...
0
2016-10-08T14:25:51Z
40,043,340
<p>The way to work around a circular import is to remove one of the imports from the module level and do it inside the method where it is used. </p> <p>You haven't shown all the model code so I don't know where you use it, but if it's in <code>save</code> it would look like this:</p> <pre><code>def save(self, **kwarg...
1
2016-10-14T12:36:36Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
Non-greedy matching of Word in pyparsing?
39,933,553
<p>I would like to match a word that ends with either <code>_foo</code> or <code>_bar</code>. I wrote this: </p> <pre><code>identifier = Word(alphanums + '_') string = identifier + Suppress('_') + oneOf('foo bar') </code></pre> <p>Unfortunately, I realized <code>identifier</code> is greedy and consume all the key...
2
2016-10-08T14:28:01Z
39,934,768
<p>Once you know for what you're looking, you can use <a href="http://pyparsing.wikispaces.com/share/view/1552279" rel="nofollow"><code>pp.SkipTo</code></a>:</p> <pre><code>In [38]: foo_or_bar = Literal('foo') | Literal('bar') In [39]: string = SkipTo(Literal('_') + foo_or_bar) + Literal('_') + foo_or_bar In [42]: s...
2
2016-10-08T16:35:44Z
[ "python", "pyparsing", "non-greedy" ]
Non-greedy matching of Word in pyparsing?
39,933,553
<p>I would like to match a word that ends with either <code>_foo</code> or <code>_bar</code>. I wrote this: </p> <pre><code>identifier = Word(alphanums + '_') string = identifier + Suppress('_') + oneOf('foo bar') </code></pre> <p>Unfortunately, I realized <code>identifier</code> is greedy and consume all the key...
2
2016-10-08T14:28:01Z
39,935,874
<p>If you have to/can switch to the re api you can use non-greedy matching there:</p> <pre><code> import re p = re.compile (r"""([a-z_]+?) # lazy matching identifier _ (bar|foo) # _ with foo or bar """, re.VERBOSE) subject_string = 'a_hello_foo' m = p.match( s...
1
2016-10-08T18:28:18Z
[ "python", "pyparsing", "non-greedy" ]
MultiProcessing slower with more processes
39,933,568
<p>I have a program written in python that reads 4 input text files and writes all of them into a list called <code>ListOutput</code> which is a shared memory between 4 processes used in my program (I used 4 processes so my program runs faster!)</p> <p>I also have a shared memory variable called <code>processedFiles</...
2
2016-10-08T14:29:19Z
39,933,783
<p>The problem is that what <em>looks</em> like multiprocessing often isn't. Just using more cores doesn't mean doing more work.</p> <p>The most glaring problem is that you synchronize everything. Selecting files is sequential because you lock, so there is zero gain here. While you are reading in parallel, every line ...
4
2016-10-08T14:51:32Z
[ "python", "multithreading", "multiprocessing" ]
MultiProcessing slower with more processes
39,933,568
<p>I have a program written in python that reads 4 input text files and writes all of them into a list called <code>ListOutput</code> which is a shared memory between 4 processes used in my program (I used 4 processes so my program runs faster!)</p> <p>I also have a shared memory variable called <code>processedFiles</...
2
2016-10-08T14:29:19Z
39,933,916
<p>Just to add to existing answer, there are certain cases where using <code>multiprocessing</code> really adds value and saves time:</p> <ol> <li>Your program does <em>N</em> tasks, which are independent of each other.</li> <li>Your program does extensive heavy mathematical calculations</li> <li>As a gotcha to second...
2
2016-10-08T15:05:37Z
[ "python", "multithreading", "multiprocessing" ]
Python - PyQt Signals - Emit and send argument to different class
39,933,593
<p>This is only my second question here so please do bear with me. I have a python script that currently contains two classes. One of which manages a GUI and the other is my 'worker thread' (a pyqt thread) . In order for me to be able to update the GUI from the 'worker thread' I understand that I can setup pyqt signals...
0
2016-10-08T14:31:46Z
39,933,960
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import time import sys from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar from PyQt5.QtCore import QThread, pyqtSignal class Thread(QThread): progress = pyqtSignal(int) def __init__(self): super(Thread, self).__init__() def __de...
0
2016-10-08T15:10:04Z
[ "python", "multithreading", "signals-slots" ]
TypeError: relative imports require the package argument in python
39,933,604
<p>I just started learning Python(2.7) and facing an issue. I am using windows 10.</p> <p>I have created a virtual environment(c:\virtualenvs\testenv) and activated it. My app folder path is c:\pyprojects\pytest. This folder has got requirements.txt with all the packages listed.</p> <p>The prompt looks like</p> <pre...
0
2016-10-08T14:33:07Z
39,934,050
<p>DJANGO_SETTINGS_MODULE is expected to be a Python module identifier, not a filesystem path. Looking at the django/conf/__init__py file, it seems that a relative path to your settings module won't work there. You will need to move it below a directory listed in your sys.path, or you should add a parent directory to y...
0
2016-10-08T15:19:10Z
[ "python", "django", "python-2.7" ]
how to check in a pandas DataFrame entry exists by (index, column)
39,933,630
<p>I have searched and searched but I can't find how to test whether a pandas data frame entry exists by (index, column).</p> <p>for example:</p> <pre><code>import pandas df = pandas.DataFrame() df.ix['apple', 'banana'] = 0.1 df.ix['apple', 'orange'] = 0.1 df.ix['kiwi', 'banana'] = 0.2 df.ix['kiwi', 'orange'] = 0.7 ...
1
2016-10-08T14:36:11Z
39,933,808
<p>You can check for the existence in index and columns:</p> <pre><code>('kiwi' in df.index) and ('apple' in df.columns) </code></pre> <p>Or you can use a try/except block:</p> <pre><code>try: df.ix['kiwi', 'apple'] += some_value except KeyError: df.ix['kiwi', 'apple'] = some_value </code></pre> <p>Note tha...
0
2016-10-08T14:54:22Z
[ "python", "pandas" ]
unorderable types: dict() <= int() in running OneVsRest Classifier
39,933,633
<p>I am running a multilabel classification on the input data with 330 features and about 800 records. I am leveraging RandomForestClassifier with following param_grid:</p> <pre><code>&gt; param_grid = {"n_estimators": [20], &gt; "max_depth": [6], &gt; "max_features": [80, 150], &gt; ...
0
2016-10-08T14:36:23Z
39,938,000
<p>Why are you trying to initialize RandomForestClassifier with parameter grid?</p> <p>If you want to do a Grid Search - look at examples here: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" rel="nofollow">http://scikit-learn.or...
1
2016-10-08T22:25:39Z
[ "python", "scikit-learn", "sklearn-pandas" ]
python raspberry pi digital dashboard for electric car
39,933,648
<p>For my master thesis we are building an electric car. For this I need to create a digital dash to show speed, rpm of the electric motor, temperatures,...</p> <p>I can program in python, but no experience in creating a interface like this. I searched on the internet for examples of digital dashes and found some nice...
0
2016-10-08T14:37:30Z
39,933,851
<p>Try wxpython for the UI design. Works great. Recently I've designed a UI for Raspi on wxpython itself.</p> <p>have a look</p> <p><a href="https://www.dropbox.com/s/f83dkc9hjhdbbdk/14632693_1206330069428934_64955080_o.png?dl=0" rel="nofollow">https://www.dropbox.com/s/f83dkc9hjhdbbdk/14632693_1206330069428934_64955...
1
2016-10-08T14:59:00Z
[ "python", "raspberry-pi", "pyqt5" ]
Cassandra sometimes throws unauthorized error
39,933,659
<p>We have a multi-node Cassandra cluster and we use Cassandra python driver for our insert queries. Everything was fine till we removed one of our nodes from the cluster using following command:</p> <pre><code>nodetool removenode force </code></pre> <p>Now our driver meets following error not always but once in a w...
1
2016-10-08T14:38:17Z
39,936,452
<p>Since you forced a remove node data may now be inconsistent you should start with a repair on the <code>system_auth</code> keyspace.</p> <p>I would then follow up with a full repair of all the other keyspaces.</p>
2
2016-10-08T19:24:38Z
[ "python", "cassandra", "unauthorized" ]
Implementing raw input in a method
39,933,701
<p>I have the following class below but struggling to make the script work as intended. </p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() books = [] for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass()...
0
2016-10-08T14:42:04Z
39,933,759
<p>You are setting <code>books</code> properly with the line <code>books = enter.split()</code>. The next line <code>books = []</code> <em>overwrites</em> this value with an empty array, so the loop never happens. </p> <p>Removing that one line, it works as expected:</p> <pre><code>&gt;&gt;&gt; class firstClass: ... ...
1
2016-10-08T14:48:15Z
[ "python", "python-2.7" ]
Implementing raw input in a method
39,933,701
<p>I have the following class below but struggling to make the script work as intended. </p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() books = [] for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass()...
0
2016-10-08T14:42:04Z
39,933,770
<p>Just remove 5th line, your code will work fine.</p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass() mybooks.test() </code></pre>
0
2016-10-08T14:49:52Z
[ "python", "python-2.7" ]
Selecting a pandas dataframe by name string generated within the code
39,933,704
<p>I'm writing up few lines in python where I have created 3 pandas dataframes DF_A, dF_B, dF_C. In the next step I do something &amp; read a string. If the string = 'A' then I want to go to dF_A(&amp; so on for B&amp;C). Any help on how this can be done?</p> <pre><code>DF = pd.ExcelFile('File.xlsx') DF_A = Dev.parse(...
0
2016-10-08T14:42:23Z
39,933,791
<p>It is possible to use <code>vars()</code>, though it's hacky</p> <pre><code>for i in tmp: # do not iterate by index table = vars()['DF_' + i] </code></pre> <p>It is cleaner to just store tables in a dictionary in the first place</p> <pre><code>tables = {} for i in ['A', 'B', 'C']: tables[i] = Dev.parse(i...
1
2016-10-08T14:52:21Z
[ "python", "pandas" ]
Consecutive values?
39,933,813
<p>Learning python, but having trouble telling function to find consecutive locations with same values. When I run the code, there's no errors but gives out the incorrect output. Suggestions on what to change?</p> <pre><code>def same_values(xs): same = False for i in (xs): if xs == xs[1:]: ...
0
2016-10-08T14:55:08Z
39,933,877
<p>So you are looking for a consecutive pair in the list and returning true if you find one. </p> <pre><code>def same_values(xs): for i in range(len(xs)-1): if xs[i] == xs[i+1]: return True return False &gt;&gt;&gt; same_values('misses') True &gt;&gt;&gt; same_values('mises') False </code>...
3
2016-10-08T15:01:29Z
[ "python", "function" ]
Importing image into Tkinter - Python 3.5
39,933,831
<p>I'm majorly struggling to import an image into <strong>Tkinter</strong> for <strong>Python 3.5</strong>, this is for my A2 project and have hit a brick wall with every method of <strong>importing a .JPG file</strong> to my window. What I have below is my GUI layer for another window, based off another thread I found...
-1
2016-10-08T14:57:14Z
39,937,321
<p>First check the path if with the correct path still persist the error "no such file or directory" please edit and put the newest version of your code. If the error is "couldn't recognize data in image file" you can correct using PIL</p> <pre><code> [...] from PIL import ImageTk [...] photo = ImageTk.PhotoImage...
0
2016-10-08T21:00:45Z
[ "python", "image", "import", "tkinter", "tk" ]
trying to sort a user input list
39,933,862
<p>Im new at python. Im creating a script that allows a user to input three names and then the code should print the names and then print them sorted (alphabetically). I can get the code to return the sorted individual letters, but not the full names as strings. I really want to run AS A LOOP!!!here is what i have s...
0
2016-10-08T15:00:43Z
39,934,845
<pre><code>print "Enter three names\n" a = raw_input("Enter first name: ") b = raw_input("Enter second name: ") c = raw_input("Enter third name: ") names = [a, b, c] print a, b, c for name in sorted(names): print name </code></pre>
0
2016-10-08T16:44:05Z
[ "python", "loops", "sorting" ]
trying to sort a user input list
39,933,862
<p>Im new at python. Im creating a script that allows a user to input three names and then the code should print the names and then print them sorted (alphabetically). I can get the code to return the sorted individual letters, but not the full names as strings. I really want to run AS A LOOP!!!here is what i have s...
0
2016-10-08T15:00:43Z
39,935,093
<p>you can use a list in python it has a good function called sort you can call it from list code <br></p> <pre><code>print ('Enter three names, when done hit enter with a blank: ') a = (raw_input('enter first name: ')) b = (raw_input('enter first name: ')) c = (raw_input('enter first name: ')) my_list = [a,b,c] m...
1
2016-10-08T17:10:35Z
[ "python", "loops", "sorting" ]
variables not defined in if statements for change counting program
39,933,883
<p>I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could ...
1
2016-10-08T15:02:07Z
39,934,094
<p>Your conditional logic is flawed. You are never assessing the grade (<code>letter</code>) if the <code>score.isdigit()</code>:</p> <pre><code>while scores != 'done': scores=input("Enter Homework score: ") if scores.isdigit(): numeric=int(scores) percentage=(numeric*10/count) if perce...
2
2016-10-08T15:24:44Z
[ "python" ]
variables not defined in if statements for change counting program
39,933,883
<p>I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could ...
1
2016-10-08T15:02:07Z
39,934,204
<p>Your code should look similar to the one below. Although I still cannot assess the logic behind your program (because you did not explain that in your question, e.g. <code>percentage=(numeric*10/count)</code> does not seem quite right to me, etc.), but the code below solves your current problem (based on your curren...
0
2016-10-08T15:36:10Z
[ "python" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it return...
2
2016-10-08T15:02:10Z
39,933,925
<p>In a return under condition <code>a_list[mid] &lt; item</code> change the line</p> <pre><code>return binary_search(a_list[mid:], item) + mid </code></pre> <p>To the line</p> <pre><code>return binary_search(a_list[mid+1:], item) </code></pre> <p>Now the <code>mid</code> element gets included to the new list</p> ...
1
2016-10-08T15:06:22Z
[ "python", "binary-search" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it return...
2
2016-10-08T15:02:10Z
39,934,083
<p>Try this.</p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list while len(a_list) &gt; 0: if len(a_list) == 1 and a_list[mid] != item: return False elif a_li...
0
2016-10-08T15:23:28Z
[ "python", "binary-search" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it return...
2
2016-10-08T15:02:10Z
39,934,554
<p>Here is the code I used to examine your program. <code>pdb</code> allows you to step through the code one command at a time using <code>s</code> or continue to the next <code>pdb.set_trace()</code> using <code>c</code>. You use it like this:</p> <pre><code>import pdb def binary_search(a_list, item): if not a_...
1
2016-10-08T16:14:03Z
[ "python", "binary-search" ]
UPLOAD file to django
39,934,078
<p>I try to upload a file to django from html through an ajax call.</p> <p>CLIENT SIDE:</p> <pre><code>&lt;input type="file" class="text-field" name="media"&gt; &lt;input type="button" class="btn" value="SEND"&gt; var files; $('.text-field').change(function(){ files = this.files; ...
1
2016-10-08T15:21:56Z
39,934,230
<p>To upload a file through Django, you will most likely have to use django forms. Here is an example as for how to upload a file:</p> <pre><code>def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = ModelWithFileField(f...
0
2016-10-08T15:38:26Z
[ "python", "django", "file" ]
Object is not callable
39,934,169
<p>I make this condition:</p> <pre><code>if ((liste_mois[0]==3) or (liste_mois[0]==6) (liste_mois[0]==9) or (liste_mois[0]==12)) </code></pre> <p>i got: TypeError: 'bool' object is not callable</p>
0
2016-10-08T15:31:39Z
39,934,217
<p>you missed an "or" in between.</p>
1
2016-10-08T15:37:07Z
[ "python", "python-2.7", "odoo-8" ]
Object is not callable
39,934,169
<p>I make this condition:</p> <pre><code>if ((liste_mois[0]==3) or (liste_mois[0]==6) (liste_mois[0]==9) or (liste_mois[0]==12)) </code></pre> <p>i got: TypeError: 'bool' object is not callable</p>
0
2016-10-08T15:31:39Z
39,934,286
<p>You've got:</p> <blockquote> <p>TypeError: 'bool' object is not callable</p> </blockquote> <p>just because you're doing something like that:</p> <pre><code>(liste_mois[0]==6) (liste_mois[0]==9) </code></pre> <p>which could be represented as, let's say:</p> <pre><code>(True) (False) </code></pre> <p>and going...
1
2016-10-08T15:44:02Z
[ "python", "python-2.7", "odoo-8" ]
Python: remove files older than X days
39,934,173
<p>I have this script to remove all images from a server directory:</p> <pre><code>import ftplib ftp = ftplib.FTP("server", "user", "pass") files = ftp.dir('/') ftp.cwd("/html/folder/") filematch = '*.jpg' target_dir = '/html/folder' import os for filename in ftp.nlst(filematch): ftp.delete(filename) </code></pre> ...
0
2016-10-08T15:32:29Z
39,934,341
<p>In python 3.3+ was added <code>mlsd</code> command support, which allows you to get the <code>facts</code> as well as list the directory.</p> <p>So your code should be like this:</p> <pre><code>filematch = '.jpg' target_dir = '/html/folder' import os for filename, create, modify in ftp.mlsd(target_dir, facts=['cr...
0
2016-10-08T15:50:15Z
[ "python", "ftp" ]
fors in python list comprehension
39,934,187
<p>Consider I have nested for loop in python list comprehension</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for x in data for y in x] [0, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; [y for y in x for x in data] [6, 6, 6, 7, 7, 7, 8, 8, 8] </code></pre> <p>I can't explain why is that ...
4
2016-10-08T15:34:25Z
39,934,209
<p>It's holding the value of the previous comprehsension. Try inverting them, you'll get an error</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for y in x for x in data] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is no...
6
2016-10-08T15:36:21Z
[ "python", "list", "python-2.7", "for-loop", "list-comprehension" ]
fors in python list comprehension
39,934,187
<p>Consider I have nested for loop in python list comprehension</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for x in data for y in x] [0, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; [y for y in x for x in data] [6, 6, 6, 7, 7, 7, 8, 8, 8] </code></pre> <p>I can't explain why is that ...
4
2016-10-08T15:34:25Z
39,934,236
<p>The list comprehensions are as:</p> <pre><code>[y for x in data for y in x] [y for y in x for x in data] </code></pre> <p>A <code>for</code> loop conversion of <code>[y for y in x for x in data]</code> is:</p> <pre><code>for y in x: for x in data: y </code></pre> <p>Here <code>x</code> is holding the...
2
2016-10-08T15:38:41Z
[ "python", "list", "python-2.7", "for-loop", "list-comprehension" ]
Plotting Smith chart using PySmithPlot
39,934,233
<p>I'm trying to plot Smith chart in python using PySmithPlot, it has to be placed along some other items in frame, but i can't find a way to do so. I have managed to make plots with matplotlib, but didn't have any luck so far with Smiths chart. Can anyone give me a reference to a site where i could find explanation t...
-1
2016-10-08T15:38:31Z
39,935,375
<p><code>PySmithPlot</code> provides a new <code>projection</code> which you can pass to e.g. <code>subplot()</code> or <code>add_subplot()</code>:</p> <pre><code>import matplotlib.pylab as pl import smithplot from smithplot import SmithAxes fig = pl.figure() ax1 = fig.add_subplot(121) ax1.plot([(1, 2), (3, 4)], [...
0
2016-10-08T17:37:33Z
[ "python", "matplotlib" ]
Python Ephem sunset and sunrise
39,934,242
<p>I am trying to calculate the exact amount of daylight hours for a given day and location. I have been looking at the python module "Ephem" for the sunrise and set calculation. Here is the code below:</p> <pre><code>import ephem California_forest = ephem.Observer() California_forest.date = '2001/01/01 00:00' Califor...
2
2016-10-08T15:39:02Z
39,934,363
<p>What you really what is the string representation of your object. If you must get the string representation of it, then call the <code>__str__()</code> special method as follows.</p> <pre><code>sunrise = California_forest.previous_rising(ephem.Sun()).__str__() sunrise '2000/12/31 15:21:06' sunset = California_fore...
1
2016-10-08T15:53:29Z
[ "python", "pyephem" ]
Python Ephem sunset and sunrise
39,934,242
<p>I am trying to calculate the exact amount of daylight hours for a given day and location. I have been looking at the python module "Ephem" for the sunrise and set calculation. Here is the code below:</p> <pre><code>import ephem California_forest = ephem.Observer() California_forest.date = '2001/01/01 00:00' Califor...
2
2016-10-08T15:39:02Z
39,934,407
<p>It looks like this is returning an <code>ephem._libastro.Date</code> object, which, when <a href="https://github.com/brandon-rhodes/pyephem/blob/master/extensions/_libastro.c#L502" rel="nofollow">convrted to <code>str</code></a> returns the nicely formatted string you see when printing it.</p> <p>If you just enter ...
2
2016-10-08T15:58:24Z
[ "python", "pyephem" ]
Implementation of Divisive Clustering
39,934,252
<p>I'm referring to this <a href="http://www.cs.utexas.edu/users/inderjit/public_papers/hierdist.pdf" rel="nofollow">paper</a>. In that paper they are clustering words before classifying the document</p> <p>They say that from a document set with vocabulary size of 35000, they have been able to classify the documents a...
-2
2016-10-08T15:39:51Z
39,940,964
<p>Implement it yourself (questions asking for code/libraries are off-topic here!). Figure 1 is the pseudo-code of the proposed algorithm.</p>
0
2016-10-09T07:08:32Z
[ "python", "algorithm", "nlp", "cluster-analysis", "hierarchical-clustering" ]
How to divide file into several files using python
39,934,298
<p>I have a video file and i need to <strong>divide</strong> it into several smaller files of size <strong>256KB</strong> and save all files names in a text file then i need to read all the small files and <strong>merges</strong> them into the original file.</p> <p>is this possible to do it in <strong>python</strong> ...
0
2016-10-08T15:45:30Z
39,934,510
<p>First stab at splitting:</p> <pre><code>input_file = open(input_filename, 'rb') blocksize = 4096 chunksize = 1024 * 256 buf = None chunk_num = 0 current_read = 0 output_filename = 'output-chunk-{:04d}'.format(chunk_num) output_file = open(output_filename, 'wb') while buf is None or len(buf) &gt; 0: buf = input_...
1
2016-10-08T16:08:43Z
[ "python", "python-2.7", "python-3.x" ]
Python 3 Beautiful Soup find tag with colon
39,934,304
<p>I am trying to scrape this site and get two separate tags. This is what the html looks like.</p> <pre><code>&lt;url&gt; &lt;loc&gt; http://link.com &lt;/loc&gt; &lt;lastmod&gt;date&lt;/lastmode&gt; &lt;changefreq&gt;daily&lt;/changefreq&gt; &lt;image:image&gt; &lt;image:loc&gt; https://imagelin...
1
2016-10-08T15:45:59Z
39,934,355
<p>You should parse it in <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">"xml" mode</a> instead (requires <code>lxml</code> to be installed as well):</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;url&gt; &lt;loc&gt; http://link.com &lt;/loc&gt...
1
2016-10-08T15:52:38Z
[ "python", "python-3.x", "tags", "beautifulsoup", "bs4" ]
Construct a data structure with special requirements in python
39,934,347
<p>Requirements:</p> <ol> <li>There is a variable, for example, related_to_dict = 10</li> <li>Construct a key value pair data, for example, special_dict = {0 : ref_related_to_dict}</li> <li>When the variable of related_to_dict changed, the value of special_dict[0] also changed to the value of related_to_dict according...
0
2016-10-08T15:50:55Z
39,934,378
<p>You need to wrap the value in some sort of container. </p> <pre><code>class Ref: def __init__(self, v): self.val = v </code></pre> <p>And then:</p> <pre><code>related_to_dict = Ref(10) special_dict = {0: related_to_dict} </code></pre> <p>Then it works as desired:</p> <pre><code>related_to_dict.val = ...
1
2016-10-08T15:55:10Z
[ "python", "data-structures" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import s...
0
2016-10-08T16:02:50Z
39,934,640
<p>To read the last line of a big file, pick a position near the end of the file and read. If there are no newlines there, go back a little and read again.</p> <p>Then find the last newline and the rest is your last line.</p> <pre><code>EXPECTED_MAX_LINE_SIZE = 500 # this should be both small enough and big enough ...
0
2016-10-08T16:21:52Z
[ "python", "search", "raspberry-pi", "pulse" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import s...
0
2016-10-08T16:02:50Z
39,934,779
<p>Your logic is way over complicated, if you will be running the script different times just store the last index in a separate file constantly overwriting:</p> <pre><code> def next_index(index): with open(index, 'a+') as f: # open for reading. If it does not exist, create it val = int(next(f, -1)) + 1 #...
0
2016-10-08T16:37:02Z
[ "python", "search", "raspberry-pi", "pulse" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import s...
0
2016-10-08T16:02:50Z
39,941,876
<p>I don't think that was what Padraic Cunningham meant, but I've managed to solve my problem by using two files, one for logging the updated index value, and one for storing the values :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import signal #verbose = True # globa...
0
2016-10-09T09:10:12Z
[ "python", "search", "raspberry-pi", "pulse" ]